multiple messages are recieved on content page when just one is sent?

独自空忆成欢 提交于 2019-12-12 02:52:51

问题


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,

  1. Remove "all_frames" part or set it false
  2. 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);
    }
    
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!