简体   繁体   中英

Firefox WebExtension, run script once on page load

my current script is designed to redirect the page if it has a URL in an array. My script will (I think) redirect the page but then continue to redirect it (resulting in a constantly loading page). Is there a way to only run the script once or end the script?

Script:

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());

Both the below attempts did not work either:

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;
}

and

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) {

};

My script is currently run via "content_scripts" :

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

First off, since content scripts are not injected into chrome-extension: pages, for a blocked URL you won't get any loops.

However, you do risk a loop for URLs that aren't blocked, since even if you assign the same value to window.location , it will reload the page.

Further, passing a real URL to chrome.runtime.getURL() will mangle it - so, fortunately, you won't get loops, but you wouldn't be able to visit any page either.

So, your code should simply not assign in the "allowed" case.

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

(Method used: Array.prototype.includes )

That said, you're using a wrong tool for the job. The proper approach to take is to use webRequest API. It would allow you to redirect far more efficiently than that and is specifically designed for the job. See examples from Chrome docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM