问题
when i send on message even then four times the alert is triggering ! don't know what is wrong ! I am adding the manifest too.
background.js :
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.method == "123")
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"});
})
}
});
content.js :
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.method);
if (request.method == "xyz"){
alert("hello);
}
});
this is the the manifest file manifest :
{
"manifest_version" : 2,
"version" : "0.1.0.0",
"name" : "xyz",
"short_name": "xyz",
"permissions" : [" <all_urls>","tabs","storage","notifications","unlimitedStorage","downloads"],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>","http://*/*","https://*/*"],
"js": [
"content.js",
],
"all_frames" : true
}],
"browser_action" : {
"default_title" : "test",
"default_popup" : "popup.html"
},
"devtools_page" : "xyz.html"
}
回答1:
You have declared "all_frames": true
in your manifest.json
, which means your content scripts will be injected into every iframe in your webpage, then when message is sent from background page, every listener in content script will respond to that.
To solve this,
- Remove
"all_frames"
part or set itfalse
If you do want you scripts to be injected into frames and only want to respond to message in top window, you could detect the content script by checking
window !== window.top
if (window !== window.top) { chrome.runtime.onMessage.addListener(callback); }
Or exclude the iframes when sending the message:
chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"}, {frameId: 0});
来源:https://stackoverflow.com/questions/36857806/multiple-messages-are-recieved-on-content-page-when-just-one-is-sent