我在持久后台脚本(background.js)中有以下代码:
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
当我在 Chrome 中加载/重新加载扩展程序时,我收到错误消息
Uncaught TypeError: Cannot call method 'addListener' of undefined
该代码取自 Chrome 扩展的文档站点,因此它可能是工作代码,只是缺少一些设置。
清单看起来像:
{
"manifest_version": 2,
"name": "TestMessaging",
"version": "1",
"background" : {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon" : "icon.png"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": [
"contentscript.js"
]
}
],
"permissions" : [
"tabs",
"https://*/*",
"http://*/*"
]
}
谢谢你的帮助!