Chrome 扩展 webRequest.onBeforeRequest 取消页面

Chrome Extension webRequest.onBeforeRequest Cancel Page

我正在尝试创建一个 chrome 扩展程序,该扩展程序查询外部源作为阻止或允许通过特定页面的参考。以下是我的代码的一部分。我是 javascript 的新手,范围似乎总是让我感到困惑。

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {

        var http = new XMLHttpRequest();
        var url = "http://xxx.xx.xxxx";
        var params = "urlCheck="+encodeString_(details.url);
        http.open("POST", url, true);
        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function() {
            if(http.readyState == 4 && http.status == 200) {
                guilt = 0;
                console.log(guilt);
            }else if(http.readyState == 4 && http.status == 404){
                guilt = 1;
                console.log(guilt);
            }
        }
        http.send(params);

    if(guilt == 1){
        return {cancel: true};
        }else{
        return {cancel: false};
        }

    },
    {urls: ["<all_urls>"],
     types:["main_frame"]
    },
    ["blocking"]
    );

如有任何帮助,我们将不胜感激!谢谢

你不能那样做。

您的代码没有按预期工作,因为 XHR 是异步的;您的 onreadystatechange 在整个外部函数完成后执行。所以 guilt 将是未定义的,或者更糟的是,陈旧的(来自最后一个请求)。

有关详细信息,请参阅此规范问题:Why is my variable unaltered after I modify it inside of a function?

但是,如果您尝试修复此问题,您会注意到您无法 return 来自异步处理程序的响应。

这是故意的:没有函数传递然后稍后调用(像sendResponse in Messaging API),因为Chrome 不会等待你。您应该以确定且快速的方式响应阻塞调用。

If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns.

可以尝试使用同步 XHR 调用绕过它。这通常不是一个好主意,因为加载远程响应需要很长时间,并且同步 XHR 被认为已弃用。即使您将查询限制为 "main_frame" 个请求,这仍然会增加每次加载的不确定延迟。

一个正确的方法是从服务器加载一组规则并定期更新它,当请求发生时根据这个本地规则副本验证它。这是像 AdBlock 这样的扩展使用的方法。