我正在尝试在一个或多个内容脚本与后台脚本之间建立通信。
最好的方法是什么?
我有一个Content对象和一个Background对象:如果在打开匹配的网页时重新加载Webextension,则当Content设置为标准时,Background还不存在,因此如果Content对象构造函数调用browser.runtime.connect
,控制台日志会显示“由于错误而断开连接:无法建立连接。接收端不存在”:
CONTENT SCRIPT constructor content-script.js:3:5
Disconnected due to an error: Could not establish connection. Receiving end does not exist. content-script.js:17:7
BACKGROUND constructor background.js:3:5
ON CONNECT background.js:14:5
ON INSTALLED HANDLER background.js:10:5
我想我应该在后台脚本中添加一个onInstalled
事件处理程序,该事件处理程序会向内容脚本发送一次性消息,告诉它连接其端口,但是我不知道如何等待此类消息内容脚本方面。...
这是我的background.js文件:
class Background {
constructor() {
console.log("BACKGROUND constructor");
this.channels = [];
browser.runtime.onInstalled.addListener(this.onInstalledHandler)
browser.runtime.onConnect.addListener((this.onConnect)(this));
}
onInstalledHandler() {
console.log("ON INSTALLED HANDLER");
}
onConnect(self) {
console.log("ON CONNECT");
return function(port) {
self.channels[port.sender.tab.id] = port;
}
}
onConnectErrorHandler(error) {
console.error(`Error: ${error}`);
}
}
var background = new Background();
和我的content-script.js文件:
class Content {
constructor() {
console.log("CONTENT SCRIPT constructor");
this.channel = browser.runtime.connect({
name: "port-from-cs"
});
this.channel.onDisconnect.addListener(this.onDisconnect);
browser.runtime.onMessage.addListener(this.onBackgroundMessage);
}
onDisconnect(p) {
if (p.error) {
console.log(`Disconnected due to an error: ${p.error.message}`);
}
}
onBackgroundMessage(request) {
console.log("BACKGROUND message");
}
}
var content = new Content();
最后是manifest.json:
{
"manifest_version": 2,
"name": "test",
"version": "1.0",
"applications": {
"gecko": {
"id": "test@test",
"strict_min_version": "42.0"
}
},
"permissions": ["tabs"],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.mozilla.org/*"],
"js": ["content-script.js"]
}]
}
P.S。 我是一个自学成才的初学者! ....对不起我的英语