`chrome.webRequest.onBeforeRequest.removeListener`?-- 如何停止 chrome 网络侦听器 [英] `chrome.webRequest.onBeforeRequest.removeListener`? -- How to stop a chrome web listener

查看:41
本文介绍了`chrome.webRequest.onBeforeRequest.removeListener`?-- 如何停止 chrome 网络侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在查看chrome.webrequest的CatBlock扩展示例的示例代码,我看到它用

So I was checking out the sample code for the CatBlock extension sample for chrome.webrequest, and I saw that it opened the listener with

chrome.webRequest.onBeforeRequest.addListener

所以当我想关闭它时,我可以这样做吗

So when I want to close it, can I just do

chrome.webRequest.onBeforeRequest.removeListener?

如果没有,我该如何摆脱它?

If not, how would I get rid of it?

我认为这类似于 Javascript 的本机事件侦听器,但我知道 Chrome 扩展程序中使用的事件侦听器略有不同.

I think this is similar to Javascript's native event listener, but I know the one used in Chrome's extensions is a little different.

谢谢!

万维网

推荐答案

首先,完整文档 可在此处获得.

addListener 函数通常1 有一个参数,该函数将在事件触发时作为回调执行.

addListener function normally1 has one argument, the function that will be executed as a callback when the event fires.

可以传递命名函数、变量中引用的函数或匿名函数:

One can pass a named function, a function referenced in a variable, or an anonymous function:

function callback_named (parameters) { /* ... */ }

callback_variable = function (parameters) { /* ... */ };

chrome.webRequest.onBeforeRequest.addListener(callback_named);
chrome.webRequest.onBeforeRequest.addListener(callback_variable);
chrome.webRequest.onBeforeRequest.addListener(function (parameters) { /* ... */ });

要删除侦听器,请使用相同的函数引用调用 removeListener.在匿名函数的情况下,这显然是不可能的.所以,只能删除前两个:

To remove a listener, you call removeListener with the same function reference. It's obviously impossible in case on an anonymous function. So, only the first two can be removed:

chrome.webRequest.onBeforeRequest.removeListener(callback_named);
chrome.webRequest.onBeforeRequest.removeListener(callback_variable);

请注意,您还可以测试特定的侦听器:

Note that you can also test for a particular listener:

if(chrome.webRequest.onBeforeRequest.hasListener(callback_named)){
  // callback_named is listening
}

或者,测试是否有监听器:

Or, test if there are listeners at all:

if(chrome.webRequest.onBeforeRequest.hasListeners()) {
  // something is listening
}

<小时>

1 某些 API 甚至允许过滤和/或在回调参数之后出现的其他选项.事实上,webRequest API 就是这样的例子之一,这使得上面的例子并不完全正确(过滤器对于这个 API 是必需的).但他们回答了问题的本质.


1 Some APIs allow for even filtering and/or additional options, which come after the callback argument. In fact, webRequest API is one of such instances, which make the above examples not entirely correct (filters are mandatory for this API). But they answer the essence of the question.

这篇关于`chrome.webRequest.onBeforeRequest.removeListener`?-- 如何停止 chrome 网络侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆