我有 Opera 侧边栏扩展
当扩展被触发(sb 打开)时,我需要在事件选项卡中注入(inject)一些带有消息监听器的代码
代码工作正常,问题是,如果我关闭侧边栏并再次打开它,我将注入(inject)另一个监听器(发送消息时控制台将记录两次)...并且在另一个重新打开+1...等等。
我尝试通过删除监听器来解决此问题,但它不起作用。
每次新扩展启动(注入(inject))时,我仍然会在控制台上获得 +1。
我无法将 addListener 放置在 removeListener 回调中。根本不起作用
(我猜它不支持这种形式)
这是我注入(inject)的代码:
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);
});
注入(inject)新监听器时如何清除先前的监听器?
最佳答案
在您的代码中,每次都会重新创建 msgL
函数,因此 removeListener
尝试删除此新实例而不是之前附加的实例。
将函数存储在window
对象中(这看起来不安全),注入(inject)的代码将是:
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);
});
}
});
此代码在持久后台页面中运行时将保存 attachedID
。否则,请使用 sessionStorage
API 或 chrome.storage
API 保存/恢复它。
关于javascript - 从注入(inject)的脚本中删除监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31907963/