使用 webRequest API 取消阻止 url 通过删除阻止它的侦听器

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

从这里得到线索后 post Post

我正在尝试删除一个侦听器(它使用 webRequest api 阻止了 URL)以取消阻止 URL。 但是我无法成功删除它,我正在做这样的事情...

要屏蔽URL

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

解锁 URL

chrome.webRequest.onBeforeRequest.removeListener(blockListener);

我做错了什么?

您在添加侦听器时使用了命名函数,以便将其作为参数传递,此外,您只传递要删除的侦听器,这应该是第二个参数,在您定义了从中发出的事件之后您正在删除侦听器。但是,这不是正确的方法。相反,你应该单独定义你的函数,比如

    function blockListener(details) {
        // Your code
    }

然后将其用于 add/remove 个听众。

下面的代码片段有一个 div,其中有一个内部文本,您可以点击该文本 5 秒钟,然后停止收听。您可以尝试一下,并在测试期间查看日志。

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>