我正在尝试构建一个 Google Chrome 扩展程序,它可以从内容脚本向后台页面发送消息,并根据发送的消息显示警报。
Manifest.json
{
"manifest_version": 2,
"name": "fb_rainbow",
"description": "Change Facebook Themes Colors",
"version": "1.1",
"background": {
"page":"background.html"
},
"browser_action": {
"default_icon": "icon.png",
"popup":"popup.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*",
"notifications",
"contextMenus",
"background"
],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"web_accessible_resources":["injectin.js"],
"content_scripts": [
{
"matches": ["*://*.facebook.com/*"],
"js": ["color_change.js"]
}
]
color_change.js(有效并且可以获得警报)
chrome.extension.sendMessage( {message:'execute'} , function() { alert('message sent!'); });
背景.html
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.message=="execute"){
alert("message received!");
}else if{
alert("message not received!");
}
});
但我没有收到来自后台页面的任何警报。
最佳答案
代码中的问题
if(request.message=="execute"){
alert("message received!");
}else if{
alert("message not received!");
}
Java 脚本中没有 else if{
,请使用 else {
。
工作版本
背景.html
<html>
<head>
<script src="background.js"></script>
</head>
<body>
</body>
</html>
背景.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.message=="execute"){
alert("message received!");
}else{
alert("message not received!");
}
});
关于javascript - Chrome 扩展程序将消息传递到后台页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15016855/