仅发送一封邮件时,内容页面上会收到多封邮件? [英] multiple messages are recieved on content page when just one is sent?

查看:177
本文介绍了仅发送一封邮件时,内容页面上会收到多封邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我发送消息时,甚至触发警报四次! 不知道怎么了! 我也在添加清单.

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:

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:

content.js :

chrome.runtime.onMessage.addListener(
    function(request) {
        alert(request.method);
        if (request.method == "xyz"){   
            alert("hello);
         }
});

这是清单文件 清单:

{
"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" 

}

推荐答案

您已经在manifest.json中声明了"all_frames": true,这意味着您的内容脚本将被注入到网页中的每个iframe中,然后从后台页面,内容脚本中的每个侦听器都会对此进行响应.

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.

要解决此问题,

  1. 删除"all_frames"部分或将其设置为false
  2. 如果您确实希望将脚本注入帧中并且只想在顶部窗口中响应消息,则可以通过选中window !== window.top

  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);
}

  • 或在发送邮件时排除iframe:

  • Or exclude the iframes when sending the message:

    chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"}, {frameId: 0});
    

  • 这篇关于仅发送一封邮件时,内容页面上会收到多封邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆