我希望能够从内容脚本(任何标签)到背景沟通。Chrome扩展onMessage.addListener在background.js不会被调用
根据文件,我应该使用
chrome.extension
chrome.runtime.onMessage
与chrome.runtime.sendMessage
。
所以这就是我所做的:
的manifest.json
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"*://*/*"
],
background.js
console.info('1');
chrome.runtime.onMessage.addListener((request, sender, sendReponse) => {
console.info('2');
sendReponse({ msg: 'foo' });
return true;
});
我不是很肯定return true;
is needed。我尝试了和没有。
建设和重装扩展后,我通过chrome://extensions
> 1 // background.js file was run
> chrome.runtime.sendMessage({ hello: 'so' }, v => console.info(v))
> undefined
> undefined // This is the callback response I get. Why?
更重要的访问镀铬背景页,我也从其他选项卡(即stackoverflow.com)
> chrome.runtime.sendMessage('extension id', { hello: 'so' }, v => console.info(v))
> undefined
> undefined
运行时的sendMessage得到一个空的响应回调 为什么我会得到一个空响应回调?
我是否缺少特别许可?错误的参数?也许错误的API函数这样做?
至于'返回TRUE',它仅在需要时响应从一个[异步执行的代码]传送(https://stackoverflow.com/a/14220323)。 – wOxxOm