Reputation: 53
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"]
}
]
Upvotes: 1
Views: 1003
Reputation: 77571
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.
Upvotes: 3