It’s just a syntax problem. The correct syntax is:
if (condition || otherCondition) {
// Do something
}
Which in your case translates to:
if (
document.querySelector('meta[name="title"]').content.includes("news") ||
document.querySelector('meta[name="description"]').content.includes("news") ||
document.querySelector('meta[name="tags"]').content.includes("news")
) {
window.open("https://google.com/", "_self");
}
However, running this against the BBC website highlights a further error.
These are the meta tags they have in the head section of their site:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="description" content="Breaking news, sport, TV, radio and a whole lot more. The BBC informs, educates and entertains - wherever you are, whatever your age.">
<meta name="keywords" content="BBC, bbc.co.uk, bbc.com, Search, British Broadcasting Corporation, BBC iPlayer, BBCi">
<meta property="fb:page_id" content="228735667216" />
<meta property="fb:admins" content="297814326937641" />
<meta property="fb:app_id" content="187214818032936" />
<meta property="og:title" content="BBC - Homepage" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://www.bbc.com/" />
<meta name="msvalidate.01" content="A09EF0BF1FC5CDBB37D921CBC3776943" />
<meta property="wwhp-edition" content="international" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta property="fb:pages" content="228735667216" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Your script, when run against this produces:
Uncaught TypeError: document.querySelector(...) is null
This means that document.querySelector('meta[name="title"]')
returns null
(i.e. that element doesn’t exist), then you try to call .content.includes()
on null
.
You could solve this with optional chaining:
if (
document.querySelector('meta[name="title"]')?.content.includes("news") ||
document.querySelector('meta[name="description"]')?.content.includes("news") ||
document.querySelector('meta[name="tags"]')?.content.includes("news")
) {
window.open("https://google.com/", "_self");
}
which then works as expected.
However, if you want to start adding further conditions to your script, it will start to get unwieldy.
It might therefore be an idea to do it like this:
const metaTags = document.querySelectorAll('meta');
metaTags.forEach((tag) => {
console.log(tag);
if (tag?.content.includes('news')) window.location = 'https://google.com/';
});
This will check all of the page’s meta tags and redirect on the first occurrence of the word, which might or might not be what you want.