Chrome白名单扩展

时间:2019-02-18 16:05:45

标签: javascript google-chrome-extension

我正在尝试在Chrome中添加白名单扩展。运行扩展程序时出现以下错误。

Uncaught Error: Parameter 1 (filter) is required.
    at validate (extensions::schemaUtils:36)
    at validateListenerArguments (extensions::webRequestEvent:19)
    at WebRequestEventImpl.addListener (extensions::webRequestEvent:92)
    at WebRequestEvent.publicClassPrototype.(anonymous function) [as addListener] (extensions::utils:138:26)
    at window.onload (bkg.js:3)

我查看了其他几个问题,但无法找出正在发生的情况。我还用Google搜索了我的错误,但没有发现任何问题。

bkg.js(后台脚本)

window.onload = function(){

    chrome.webRequest.onBeforeRequest.addListener(
        function(details) {
            var allowed = ["*://*.google.com/*", "*://*.nbclearn.com/*"];
            chrome.tabs.getSelected(null, function(tab) {
                var tabUrl = tab.url;

                if ($.inArray(tabUrl, allowed) == -1){
                    return {
                        cancel: true
                    }
                }
                else {
                    return {
                        cancel: false
                    }
                }
            },
        {urls: ["*://*/*"]},
        ["blocking"]);
    });
};

我希望这将仅允许加载allowed数组中的网站,而其他网站将被阻止。相反,我从上面得到了错误,扩展名不执行任何操作。我要指出的错误是什么意思,该如何解决?

1 个答案:

答案 0 :(得分:1)

以下是您的代码,其中的缩进已更正:

window.onload = function(){

    chrome.webRequest.onBeforeRequest.addListener(function(details) {
        var allowed = ["*://*.google.com/*", "*://*.nbclearn.com/*"];
        chrome.tabs.getSelected(null, function(tab) {
            var tabUrl = tab.url;

            if ($.inArray(tabUrl, allowed) == -1) {
                return {cancel: true}
            } else {
                return {cancel: false}
            }
        }, {urls: ["*://*/*"]}, ["blocking"]);  // all these are chrome.tabs.getSelected arguments
    });  //chrome.webRequest addListener arguments are missing
};

如您所见,您正在将{urls: ["*://*/*"]}, ["blocking"]作为参数传递给chrome.tabs.getSelected,而不是chrome.webRequest侦听器。按照documentation示例,您可以执行以下操作:

window.onload = function(){

    chrome.webRequest.onBeforeRequest.addListener(function(details) {
        return {cancel: (details.url.indexOf("google.com/") == -1 && details.url.indexOf("nbclearn.com/") == -1)} },
        {urls: ["<all_urls>"]},
        ["blocking"]);
};

为了阻止所有来自这两个域的请求。

您可以使用Array.prototype.every将白名单中的域包含在数组中。例如:

window.onload = function(){

    var allowed = ["chrome.com/", "nbclearn.com/", "example.com/"];

    chrome.webRequest.onBeforeRequest.addListener(function(details) {
        var isForbidden = allowed.every(function(url) {
            return details.url.indexOf(url) == -1;
        });
        return {cancel: isForbidden}
    }, {urls: ["<all_urls>"]}, ["blocking"]);
};