1. 程式人生 > >一起來做Chrome Extension《一些問題》

一起來做Chrome Extension《一些問題》

ror tutorials mode man -m ani iframe proxy 解決方法

目錄

  1. Unchecked runtime.lastError: The message port closed before a response wa received.
  2. 使用 eval
  3. Content script註入iframe
    1. Extenstion內的html
    2. 站外連接

1. Unchecked runtime.lastError: The message port closed before a response wa received.

此錯誤一般發生在background js和content js通訊的時候,問題描述得也非常清楚,解決方法非常簡單,即在收到消息後,在同步時間裏send respnose就可以了。

註意:send response如果在異步方法裏,並不能解決這個問題。

// Example:
// background js 或content js
chrome.extension.onMessage.addListener(function(request, _, sendResponse) {
    sendResponse('');
});

2. 使用eval

Chrome Extension默認是禁止使用eval方法的,使用之前,需要先在manifest.json裏開啟,如下:

"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

3. 使用iframe

註入iframe同樣受content_security_policy限制,而且會受到目標站點的content_security_policy限制。關於content_security_policy內容比較多,這裏分成兩種情況

3.1 Extension內的html

註入的iframe加載Extension內的html稍微沒有這麽麻煩,只需要在manifest.json裏指定要加載的html就好了

"web_accessible_resources": ["example.html"]

註入iframe的src,可以使用chrome.runtime.getUrl()來獲取地址

let src = chrome.runtime.getURL('example.html')

註:要註入網站的content_security_policy對這樣的iframe註入會不會有影響,目前還沒有測試到。

此方法在 Fika (reader-mode) 擴展裏有使用

3.2 站外連接

如上所說,註入iframe是受目標網站的content_security_policy限制的,所以,如果目標網站不允許,你的註入將會失敗,如medium.com的content_security_policy關於frame-src的部分:

default-src ‘self‘;

...

frame-src chromenull: https: webviewprogressproxy: medium: ‘self‘;

...

它允許了https的地址,所以,註入的iframe加載https地址是沒有問題的,而http的地址將被拒絕。因為註入已經離開了Chrome Extenstion的範圍,所以,不管你怎麽對Chrome Extension的content_security_policy進行設置並不會有用。

關於content_security_policy,可以看 https://www.html5rocks.com/en/tutorials/security/content-security-policy/

一起來做Chrome Extension《一些問題》