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

前端 未结 1 793
别跟我提以往
别跟我提以往 2020-12-09 12:03

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

chrom         


        
相关标签:
1条回答
  • 2020-12-09 12:18

    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.

    0 讨论(0)
提交回复
热议问题