chrome扩展sendMessages不止一个

时间:2014-01-01 16:12:14

标签: javascript google-chrome-extension

Hello 我正在尝试向popedup窗口发送消息,但是当我关闭弹出窗口时,再次调用它(从上下文菜单中)...它显示所有最后的masseges .. 如何仅向新打开的窗口发送一条消息?

的manifest.json

{
  "manifest_version": 2,
  "name": "1tst",
  "description": "sm txt",
  "version": "0.1",
  "author": "smwn",
  "permissions": [  
                    "activeTab",
                    "tabs",
                    "contextMenus"
  ],
  "background": {
    "scripts": ["sample.js"]
  },
"content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["1.js"]
  }]
}

sample.js

function genericOnClick(info, tab,selT) {
 var vid;
var nw_tb;

      chrome.tabs.create({
                url: chrome.extension.getURL('1.html'),
                active: false
            }, function(tab) {
            vid = tab.id;
                // After the tab has been created, open a window to inject the tab
                chrome.windows.create({
                    tabId: tab.id,
                    type: 'popup',
                    focused: true
                    // incognito, top, left, ...
                    },function(chromeWindow) {
                                //vid = chromeWindow.id;
                            }
                );
      });
      chrome.windows.onCreated.addListener(function(tabb){
        nw_tb = tabb.id;
        alert("vid: "+vid+" nw_tb: "+nw_tb);
        chrome.runtime.sendMessage(vid, {statn: selT});
        return;
      });
}

var title = "Test '%s' menu item";
  var id = chrome.contextMenus.create({"title": title, "contexts":["selection"],
                                       "onclick": function(info,tab){   genericOnClick(info,tab, info.selectionText);}
                                      });

1.HTML

<!doctype html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="1.js"></script>
    </head>
    <body>

    </body>

</html>

1.js

window.onload=function(){
        chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
            console.log(sender.tab ?
                        "from a content script:" + sender.tab.url :
                        "from the extension");
            sendResponse({metroSTAT: "OK"});
            alert(request.statn);
       });
}

1 个答案:

答案 0 :(得分:0)

问题

每次调用genericOnClick()时,它都会为windows.onCreated事件注册一个新的侦听器。一旦注册,听众就会每次都触发。

解决方案

许多可能的解决方案之一是首次触发听众时“取消注册”(使用 removeListener() ):

// Replace the following block:
chrome.windows.onCreated.addListener(function(tabb){
    ...
});

// With this:
chrome.windows.onCreated.addListener(function tmpListener(tabb) {
    chrome.windows.onCreated.removeListener(tmpListener);
    ...
});