javascript 如何在 Chrome 扩展程序中删除事件侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10466567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove event listener in Chrome extension
提问by chaohuang
I am trying to remove the onRequest
listener added by chrome.extension.onRequest.addListener
after a request is made, like this:
我正在尝试删除在发出请求后onRequest
添加的侦听器chrome.extension.onRequest.addListener
,如下所示:
chrome.extension.onRequest.addListener(
function(request){
chrome.extension.onRequest.removeListener();
other_function(request);
}
);
The problem is that I don't know if this works or not. I tried chrome.extension.onRequest.hasListener
, which seems not to give the right answer, so I am wondering if there are some other ways to remove the onRequest
listener or check if the listener exists or not.
问题是我不知道这是否有效。我试过chrome.extension.onRequest.hasListener
,这似乎没有给出正确的答案,所以我想知道是否有其他方法可以删除onRequest
侦听器或检查侦听器是否存在。
Thanks!
谢谢!
回答by apsillers
removeListener
takes an argument. You need to name the listener function and then remove it by name:
removeListener
需要一个论点。您需要命名侦听器函数,然后按名称将其删除:
function doStuff(request){
chrome.extension.onRequest.removeListener(doStuff);
other_function(request);
}
chrome.extension.onRequest.addListener(doStuff);
Or, more succinctly:
或者,更简洁地说:
chrome.extension.onRequest.addListener(
function doStuff(request){
chrome.extension.onRequest.removeListener(doStuff);
other_function(request);
}
);
回答by Prakash GPz
Another simple and straight forward approach when using anonymous functions:
使用匿名函数时的另一种简单直接的方法:
chrome.runtime.onMessage.addListener(function(msg, sender, reply) {
chrome.runtime.onMessage.removeListener(arguments.callee);
});