2

我有 Opera 侧边栏扩展
,当扩展被触发(sb 打开)时,我需要在活动选项卡代码中注入一些带有消息监听器的
代码工作正常,问题是如果我关闭侧边栏并再次打开它,我会得到另一个监听器注入(发送消息时控制台将记录两次)......然后再次重新打开+1......依此类推。

我试图通过删除监听器来解决这个问题,但它不起作用。
对于每个新的扩展开始(注入),我仍然在控制台上获得 +1。
而且我不能将addListener放在removeListener回调中。根本不起作用
(我猜它不支持这种形式)

这是我注入的代码:

chrome.tabs.executeScript({code: 
    "chrome.runtime.onMessage.removeListener(msgL);\
    chrome.runtime.onMessage.addListener(msgL);\
    function msgL(msg) {\
      if (msg.test) console.log('aaaaaaaaaaaaaaaaaaaaaaaaa');\
    }"
  }, function(result) {
    if (!result) console.log(chrome.runtime.lastError);
});

注入新的监听器时如何清除以前的监听器?

4

1 回答 1

1

在您的代码中,msgL每次都会重新创建该函数,因此removeListener尝试删除此新实例而不是先前附加的实例。

将函数存储在window对象中(这似乎不安全),注入的代码将是:

if (window.msgL) chrome.runtime.onMessage.removeListener(window.msgL);
window.msgL = function(msg) {
  if (msg.test) console.log('aaaaaaaaaaaaaaaaaaaaaaaaa');
};
chrome.runtime.onMessage.addListener(window.msgL);

或者使用附加在您的扩展中的侦听器跟踪选项卡 ID,并仅在需要时添加它:

var attachedIDs = {};
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
    var id = tabs[0].id;
    if (!attachedIDs[id]) {
        attachedIDs[id] = true;
        chrome.tabs.executeScript({code: 
            "chrome.runtime.onMessage.addListener(function msgL(msg) {\
              if (msg.test) console.log('aaaaaaaaaaaaaaaaaaaaaaaaa');\
            });"
          }, function(result) {
            if (!result) console.log(chrome.runtime.lastError);
        });
    }
});

此代码将保存attachedIDs在持久背景页面中运行的时间。否则使用sessionStorageAPI 或chrome.storageAPI 来保存/恢复它。

于 2015-08-10T05:15:53.293 回答