Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`chrome.webRequest.onBeforeRequest.removeListener`? -- How to stop a chrome web listener

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?

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.

Thanks!

evamvid

like image 866
evamvid Avatar asked Apr 11 '14 00:04

evamvid


1 Answers

First off, full documentation is available here.

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) { /* ... */ });

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 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.

like image 50
Xan Avatar answered Oct 23 '22 08:10

Xan