一块儿来作Chrome Extension《一些问题》

目录

  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就能够了。javascript

注意:send response若是在异步方法里,并不能解决这个问题。html

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

2. 使用eval

Chrome Extension默认是禁止使用eval方法的,使用以前,须要先在manifest.json里开启,以下:html5

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

3. 使用iframe

注入iframe一样受content_security_policy限制,并且会受到目标站点的content_security_policy限制。关于content_security_policy内容比较多,这里分红两种状况java

3.1 Extension内的html

注入的iframe加载Extension内的html稍微没有这么麻烦,只须要在manifest.json里指定要加载的html就行了web

"web_accessible_resources": ["example.html"]

注入iframe的src,可使用chrome.runtime.getUrl()来获取地址chrome

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

注:要注入网站的content_security_policy对这样的iframe注入会不会有影响,目前尚未测试到。json

此方法在 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/