我想铬插件的创建消息传递 。 我的代码如下:
manifest.json的:
{
"name": "Sending Messages Test",
"version": "1.0",
"manifest_version": 2,
"description": "Send a Message to background.js from contentscript.js and send reply",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "That's the tool tip",
"default_popup": "popup.html"
},
// "permissions": ["tabs"],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentscript.js"]
}]
}
popup.html:
<script type="text/javascript" src="popup.js"></script>
<div style="width:200px">
<button id="button">Color all the divs</button>
</div>
popup.js:
window.onload = function() {
document.getElementById("button").onclick = function() {
// alert("in popup.js");
chrome.extension.sendMessage({
message: "coming from popup"
});
}
}
contentscript.js
chrome.runtime.onMessage.addListener( function(request, sender) {
alert("Contentscript has received a message from from background script: '" + request.message + "'");
return true;
});
background.js:
var backgroundScriptMessage = " purple monkey dishwasher";
chrome.extension.onMessage.addListener(function(request, sender) {
alert("Background script has received a message from contentscript:'" + request.message + "'");
returnMessage(request.message);
});
function returnMessage(messageToReturn) {
chrome.tabs.query({active: true}, function(tabs) {
var joinedMessage = messageToReturn + backgroundScriptMessage;
alert("Background script is sending a message to contentscript:'" + joinedMessage +"'");
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"});
});
}
当我解压在Chrome浏览器扩展插件,并点击生成图标时,看到2个警报
- 背景脚本已收到一则由contentscript:“从弹出来了”
- 背景脚本已收到一则由contentscript:紫色猴子洗碗机“从弹出来了”
并且从未示出的第三弹出其是存在于contentscript。 我试图寻找错误,但没有运气。 是否有人有一个解决方案?