我是Chrome扩展程序的新手。我正在尝试在内容脚本和background.html页面之间进行通信。 background.html 发送请求 "hello" 给内容脚本,内容脚本应该以"hello background"警告响应。但它就是不起作用。我的background.html代码如下:
function testRequest() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"});
});
}
content.js 代码:
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
alert("hello background");
}
);
popup.html的代码:
<!doctype html>
<html>
<head></head>
<body>
<form>
<input type="button" value="sendMessage" onclick="testRequest()" />
</form>
</body>
</html>
manifest.json:
:{
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
},
"background": {
"page": "background.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*",
"notifications",
"contextMenus"
],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["content.js"]
}
],
"name": "FirstExtension",
"version": "1.0"
}
请帮忙!
onMessage
的文档与实际情况不符。更多信息请参见https://dev59.com/NGgt5IYBdhLWcg3wygeb#11811936。 - Rob W