我正在为 Firefox for Android 开发一个扩展,但由于 Firefox(Android)不支持标签 API,我使用以下代码。它在 Firefox 上运行良好,但在将其移植到 Firefox Android(52 版本)时,后台脚本消息不会传递给内容脚本侦听器。
//内容脚本代码
var myPort = browser.runtime.connect({name:"port-from-cs"});
myPort.postMessage({greeting: "hello from content script"});
myPort.onMessage.addListener(function(m) {
console.log("In content script, received message from background script: ");
console.log(m.greeting);
});
//后台脚本
var portFromCS;
function connected(p) {
portFromCS = p;
portFromCS.postMessage({greeting: "hi there content script!"});
portFromCS.onMessage.addListener(function(m) {
console.log("In background script, received message from content script")
console.log(m.greeting);
portFromCS.postMessage({greeting: "hi there content script!"});
});
}
browser.runtime.onConnect.addListener(connected);
//显现
{
"version": "0.1.5",
"content_scripts": [
{
"js": [
"js/myContentScript.js",
"js/lib/jquery-1.9.1.min.js"
],
"matches": [
"<all_urls>"
],
"run_at": "document_start"
}
],
"description": "xxx",
"manifest_version": 2,
"name": "xx",
"applications": {
"gecko": {
"id": "vpt@mozilla.org"
}
},
"permissions": [
"webRequest",
"notifications",
"http://*/",
"https://*/",
"storage",
"webRequestBlocking"
],
"background": {
"scripts": [
"js/background.js"
]
},
"web_accessible_resources": [
"xxx.js"
]
}
内容脚本将消息传递给后台脚本,但后台脚本消息被 portFromCS.onMessage 侦听器捕获。我的方法正确吗?