从注入脚本中删除侦听器

remove listener from injected script

本文关键字:删除 侦听器 脚本 注入      更新时间:2023-09-26

我有Opera侧边栏扩展
当扩展被触发(sb打开)时,我需要在活动选项卡
中注入一些带有消息侦听器的代码代码工作得很好,问题是,如果我关闭侧边栏并再次打开它,我会得到另一个侦听器注入(控制台将日志发送消息时两次)…在另一个重新开放+1…等等......

我试图通过删除侦听器来修复这个问题,但它不起作用。
我仍然得到+1在控制台的每一个新的扩展启动(注入)。
我不能把addListenerremoveListener回调。根本不起作用
(我猜它不支持这种形式)

下面是我注入的代码:

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

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

在您的代码中,每次都重新创建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。否则使用sessionStorage API或chrome.storage API保存/还原