【问题标题】:Chrome Extension code (message passing?) executes multiple timesChrome 扩展代码(消息传递?)执行多次
【发布时间】:2015-10-10 03:25:28
【问题描述】:

使用 Chrome 的 OAuth 构建我的第一个 Chrome 扩展程序(用于 Gmail)。当我运行以下代码时,它通常会执行多次。当页面刷新时,从 background.js 传递给 content.js 的“Hi”消息会多次注销,而“HERE”通常会多次从 background.js 文件中注销。当我从不同的页面转到 gmail 时,这种行为似乎没有被复制,而只有当我刷新 gmail 时。我猜这与“onUpdated”事件监听器有关,但我不明白为什么它会执行多次。

注意:有趣的是,如果我关闭 gmail,刷新我的 background.js 文件,然后重新打开 gmail(或刷新它),代码似乎只执行一次。

Content.js

chrome.runtime.sendMessage({data: "hello"}, function(response) {
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log(sender.tab ?
              "from a content script:" + sender.tab.url :
              "from the extension");
  if (request.data)
    console.log(request.data)
});

Background.js

 chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
          if (changeInfo.status == 'complete') {
            chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
              chromeIdentityToken = token
              chrome.runtime.onMessage.addListener(
                function(request,sender,sendResponse){
                  console.log("HERE")

                  <Program code>

                  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                    chrome.tabs.sendMessage(tabs[0].id, {data: "Hi"}, function(response) {
                    });
                  });
                }
              );
            });
          }
        })

【问题讨论】:

  • 看起来您每次调用后台脚本时都在添加一个侦听器。您是否多次调用它而不删除旧的侦听器?
  • @Brian 避免在 cmets 中回答;你是对的,请把它变成一个答案。
  • @Xan 抱歉,不是 100% 确定...添加它作为答案。

标签: google-chrome google-chrome-extension gmail-api


【解决方案1】:

添加监听器时,您需要确保每个监听器只添加一次。您似乎多次添加了一个侦听器,而没有清理旧的侦听器,这不会覆盖旧的侦听器,它只是不断添加更多的侦听器。

例如:

chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse){
        console.log("HERE")
    });
chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse){
        console.log("HERE2")
    });

在这种情况下,第二个监听器不会覆盖第一个;您将同时打印“HERE”和“HERE2”。

【讨论】:

    猜你喜欢
    • 2011-03-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多