6
我有以下文件(gist爲方便):chrome.runtime.sendMessage內容腳本不發送消息
manifest.json的
{
"name": "testmessage",
"version": "0.1",
"manifest_version": 2,
"externally_connectable": {
"matches": ["*://www.google.com/*"]
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["*://www.google.com/*"],
"js": ["content.js"]
}
]
}
content.js
chrome.runtime.sendMessage(
"eldkfaboijfanbdjdkohlfpoffdiehnb", // PUT YOUR EXTENSION ID HERE
"foo",
function (response) {
console.log(response);
}
);
console.log("this is content.js reporting for duty");
background.js
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
console.log("background.js got a message")
console.log(request);
console.log(sender);
sendResponse("bar");
}
);
console.log("this is background.js reporting for duty");
我可以同時看到「......報到」,在各自的控制檯消息。但當加載http://www.google.com時,background.js
未收到消息。第5行content.js
在google.com的控制檯中打印undefined
。
當我在google.com控制檯中運行chrome.runtime.sendMessage("eldkfaboijfanbdjdkohlfpoffdiehnb", "foo");
時,它顯示在background.js控制檯中。
我在做什麼錯?