Google有关Chrome扩展程序开发的文档已information on passing messages between a background script and a content script。我正在尝试示例代码:
background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
content_script.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
//return true;
});
它们不包含清单文件,因此我创建了一个(和三个图标):
{
"background": {
"persistent": false,
"scripts": ["background.js", "content_script.js"]
},
"content_scripts": [ {
"js": ["content_script.js"],
"matches": ["<all_urls>"]
} ],
"description": "Test passing messages between a background script and a content script using Google's example code.",
"icons": {
"16": "img/icon_16x16.png",
"48": "img/icon_48x48.png",
"128": "img/icon_128x128.png"
},
"manifest_version": 2,
"name": "Test Google Chrome extension messaging",
"permissions": ["notifications"],
"version": "2017.8.25"
}
但是当我加载此扩展程序时,控制台会报告:
(未知)事件处理程序出错:TypeError:无法读取属性 '告别'未定义于 铬 - 延伸://ibocemgcnbijkacfkpokffkfkinmenlc/background.js:3:29
我在网上搜索了其他未定义响应的情况,还有一些sources recommended添加了return true;
。我试过了,但它没有任何区别(在上面的代码中,它被注释掉了。)
任何人都可以看到我如何才能使这个工作?谢谢!