Chrome扩展程序webRequest.onBeforeRequest重定向未重定向

时间:2018-07-28 21:03:01

标签: javascript google-chrome google-chrome-extension

我正在编写一个Chrome扩展程序,以阻止网站上的某些页面。

我这样做是通过加载一个.txt文件来填充要阻止的页面,然后将每个页面与用户加载的url进行比较,如果该URL与文件中的任何内容匹配,则将其重定向到阻止页面。但是,除了实际的重定向之外,其他所有功能都无法正常工作。

manifest.json

{
"name": "Reddit Subreddit Blocker",
"description": "Blocks access to specified subreddits.",
"version": "1.0",
"manifest_version": 2,
"background": {
    "scripts":["background.js"],
    "pages": ["blocked.html"],
    "persistent": true
  },
"permissions": [
  "webRequest",
  "*://*.reddit.com/r/*",
  "webRequestBlocking"
]
}

background.js

chrome.webRequest.onBeforeRequest.addListener(
function(details) {
    var r = new XMLHttpRequest();
    r.open("GET", chrome.extension.getURL("test.txt"), true);
    r.onreadystatechange = function(e){ 
        if (r.readyState == 4 && r.status == 200){              
            var subreddits = r.responseText.split("\n");
            var index;
            var url = details.url;

            var found = false;
            for (index = 0; index < subreddits.length && found == false; ++index){
                if (subreddits[index] === url){
                    console.log("Subreddit found.");
                    found = true;
                }
            }

            if (found == false){
                console.log("not found");
                return {cancel: false};
            }else{
                console.log("redirecting");
                return {redirectUrl: chrome.extension.getURL("blocked.html")};
            }                   
        }
    };
    r.send(null);
}, {
    urls: ["https://*.reddit.com/r/*"]
}, ["blocking"]
);

要阻止的网址存储在.txt文件的单独行中。

当我使用应该被阻止的url运行代码时,我只会得到输出:

Subreddit found.
redirecting

因此,找到了subreddit,并执行了要重定向的if语句,但实际上并未重定向。

0 个答案:

没有答案