简体   繁体   中英

Unblocking url using webRequest API by removing the listener which has blocked it

After getting a clue from this post Post

I am trying to remove a Listener (which has blocked the URL using webRequest api) to unblock the URL. But I am not able to remove it successfully, I am doing something like this...

To block the URL

chrome.webRequest.onBeforeRequest.addListener( function blockListener (details) {
                        return {
                            cancel: true
                        };
                    },{ urls: [url], types: [ 'main_frame' ] }, ['blocking'] );

To unblock the URL

chrome.webRequest.onBeforeRequest.removeListener(blockListener);

What am I doing wrong?

You are using a named function when you add a listener in order to pass it as a parameter, also, you only pass the listener to be removed, which should be the second parameter, after you define the event from which you are removing the listener. However, that's not the right approach. Instead you should define your function separately, like

    function blockListener(details) {
        // Your code
    }

and then use this to add/remove listeners.

The snippet below has a div with an inner text upon which you can click for 5 seconds and then stops listening. You can try it and watch the logs during your test.

 function clicked() { console.log("Clicked"); } document.getElementById("foo").addEventListener("click", clicked); setTimeout(function() { document.getElementById("foo").removeEventListener("click", clicked, false); console.log("No longer listening"); }, 5000);
 <div id="foo">abcd</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM