Firefox WebExtension,运行 页面加载一次脚本

Firefox WebExtension, run script once on page load

我当前的脚本设计用于在数组中包含 URL 时重定向页面。我的脚本将(我认为)重定向页面但随后继续重定向它(导致不断加载页面)。有没有办法只 运行 脚本一次或结束脚本?

脚本:

var blocked = ["http://example.org", "http://example.com"];
function check () {
    for (i = 0; i < blocked.length; i++ ) {
        var item = blocked[i];
        var url = window.location.href;
        if (blocked[i] == url) {
            return "interface/redirect.html";
        }
    }
    return url;
}
window.location = chrome.runtime.getURL(check());

以下两种尝试均无效:

var blocked = ["http://example.org", "http://example.com"];
var ran = false;
function check () {
    for (i = 0; i < blocked.length; i++ ) {
        var item = blocked[i];
        var url = window.location.href;
        if (blocked[i] == url) {
            return "interface/redirect.html"
        }
    }
    return url;
}
if (ran == false) {
    window.location = chrome.runtime.getURL( check () );
    ran = true;
}

var blocked = ["http://example.org", "http://example.com"];
function check () {
    for (i = 0; i < blocked.length; i++ ) {
        var item = blocked[i];
        var url = window.location.href;
        if (blocked[i] == url) {
            return "interface/redirect.html";
        }
    }
    return url;
}
window.location = chrome.runtime.getURL(check());
var x = 0;
while (x == 0) {

};

我的脚本目前是 运行 通过 "content_scripts":

"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "run_at": "document_start",
        "js": ["redirect.js"]
    }
]

首先,由于内容脚本未注入 chrome-extension: 页面,因此对于 阻塞 URL 你不会得到任何循环。

但是,对于 URL, 未被 阻止,您确实存在循环的风险,因为即使您将相同的值分配给 window.location,它将重新加载页面。

此外,将真实的 URL 传递给 chrome.runtime.getURL() 会破坏它 - 因此,幸运的是,您不会遇到循环,但您也无法访问任何页面。

因此,您的代码应该 而不是 在 "allowed" 情况下分配。

function check () {
    if (blocked.includes(window.location.href)) {
        window.location = chrome.runtime.getURL("interface/redirect.html");
    }
}
check();

(使用的方法:Array.prototype.includes

也就是说,您使用了错误的工具来完成这项工作。正确的做法是使用 webRequest API。它将使您能够比这更有效地重定向,并且是专门为这项工作而设计的。请参阅 Chrome 文档中的 examples