With vanilla JavaScript, I seek to run on a list of domains or URLs and do some action (checking if location.href matches one of these and if so, changing it).
let href = window.location.href;
let domainOrURL = ([
'example_1.com',
'https://www.example_2.com/some_path'
]).forEach( (item)=>{
if (href = domainOrURL) {
window.open("https://google.com/", "_self");
}
});
The above code brings:
VM740:6 Uncaught ReferenceError: domainOrURL is not defined
at :6:5
at Array.forEach ()
at :5:4
Hi @bendqh1, you’re not assigning the array to domainOrURL but the return value of the forEach() call, which is always undefined… and by the time you’re calling forEach(), the assignment hasn’t even taken place yet, hence the reference error. So you’d first need to assign that array, and then iterate over it in the next line.
But wouldn’t you actually want to check if href === item anyway? (Also note the triple = sign – you’re attempting another assignment here!)
I didn’t manage to find documentation to learn how to do that with forEach() but I think a for loop is a plausible alternative:
let href = window.location.href;
let anythingToBlock = [
'youtube.com',
'walla.co.il'
];
for (let i = 0; i < anythingToBlock.length; i++) {
if (href.includes(anythingToBlock[i])) {
window.open("https://google.com/", "_self");
}
}