Run on a list of domains or URLs and do some action

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

How would you suggest to do that?

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

Thanks, yes, for starters I will change if (href = domainOrURL) to if (href === domainOrURL), than I will try to figure out the rest.

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

Well you could actually use forEach() the same way…

const anythingToBlock = [
    'youtube.com',
    'walla.co.il'
]

anythingToBlock.forEach(url => {
  if (url === window.location.href) {
    window.open('http://example.com/')
  }
})

Or using some():

const matchesURL = [
  'youtube.com',
  'walla.co.il'
].some(url => url === window.location.href )

if (matchesURL) {
  window.open('http://example.com/')
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.