How to make an exception for an if statement in vanilla JavaScript?

I block virtually all news websites with this code:

if (
  document.querySelector('title')?.textContent.toLowerCase().includes('news') ||
  document.querySelector('meta[name="title"]')?.content.toLowerCase().includes('news') ||
  document.querySelector('meta[name="description"]')?.content.toLowerCase().includes('news') ||
  document.querySelector('meta[name="tags"]')?.content.toLowerCase().includes('news')
) {
  window.open("https://google.com/", "_self");
}

But let’s say I want to exclude a certain news website such as CNN or FoxNews.
Can I somehow add an exception for this general code like the following pseudocode?

BUT IF window.location.href.includes('cnn') DON'T DO ANYTHING

What I have tried

I have tried adding:

else if (window.location.href.includes('cnn')) {
    window.open("https://cnn.com/", "_self");
}

But it didn’t work, I was still redirected to google.com.

What you have:
if ( A OR B OR C OR D)
What you’re trying to explain:
if ( (A OR B OR C OR D) AND (NOT E))

Possibly with a further:
else if(E)
afterward.

NOTE: It may be quicker to put the NOT E part first, on account of short circuiting.

You can use toLowerCase

e.g.

instead of

document.querySelector('title')?.textContent.includes('News') ||
document.querySelector('title')?.textContent.includes('news') ||

this

document.querySelector('title')?.textContent.toLowerCase().includes('news')

Which would at least save searching through the DOM twice for the same element.

2 Likes

Thanks a lot, I have edited the code in question to fit to that suggestion.

Now I only try to figure out what m_hutley suggested me to do.

I believe that it will be easier for me psychologically to make the exception after the rule, i.e. right after the if () then {} condition-reaction is defined so to get if () then {} but not if ().

Or, say:

else if (window.location.href.includes('cnn')) {
    DON'T DO THE FIRST IF IN THIS BROWSER TAB
}

But, I doubt either is possible with the current release of JavaScript or EcmaScript.

Yeah, computers dont work that way around. They start at the top, and when you’ve got diverging codepaths, it’s solve the first one that matches, and then skip the rest.

That said, you COULD structure it as
if (is CNN) { do this}
else if (all the messy tag matches) { do this}
else { do something else}

Which is kind of the same thing as outlined above, just with the clauses inverted.

I didn’t understand what you tried to say in this comment because I humbly assume that in theory one could create a programming language that does indeed have such patterns:

  • IF (A) THEN {B} BUT NOT IF (C)
  • IF (A) THEN {B} ELSE IF (C) {PREVENT A}

There might even be programming languages with similar commands at the moment, I just personally don’t know any.

Not that I know of.
A computer doesnt have the idea of “wait dont do that instruction”… after the instruction. Each instruction to a computer is a sentence, followed by an action.

Consider the following instructions:

  1. “Fire the starting pistol.”
  1. “Register the starting order.”
  1. “Don’t fire the starting pistol.”

You must complete each instruction before revealing the next one.

I should clarify.

That does not exist. It’s not intelligent for a language engine to have to do this looping back on itself, to check backwards in the code, when there exists a logical flow that moves only forwards.

This is IF (A and NOT C) THEN { B }. Do all the tests up front, and then execute the code block. It’s why AND and OR exist.

Dear @m_hutley

A computer doesnt have the idea of “wait dont do that instruction”

I don’t think I said it exactly like that, I said it more like “Do one or more action/s and if a certain condition is met then cancel one or more of this/these action/s”.

I actually think that computers do often do that and the common term is postprocessing.

It’s not intelligent for a language engine to have to do this looping back on itself, to check backwards in the code, when there exists a logical flow that moves only forwards.

I personally don’t think that’s true because a computer which is “more human like” in that particular direction could, at least in theory, do that.
In a correct context, I think that “intelligently compiled code” could reflect that.

Automatic undo is not a common place occurrence, at least from my nearly 30 years of experience in this industry. There are transaction rollbacks, but those are typically reserved for exceptions, not change in business rules. Not only that, it makes things REALLY hard for someone else to understand if they have to come back in and maintain it later. Or even yourself six or eight months later - it’s amazing how many times I’ve come back into code I’ve written later and thought to myself “What in the WORLD was I thinking here?”

That being said, the suggestion by @m_hutley in post #7 is the most straight forward approach. I see you edited your original post to include the @rpg_digital tweak, so you get…

if (window.location.href.includes('cnn')) {
    window.open("https://cnn.com/", "_self");
}
else if (
  document.querySelector('title')?.textContent.toLowerCase().includes('news') ||
  document.querySelector('meta[name="title"]')?.content.toLowerCase().includes('news') ||
  document.querySelector('meta[name="description"]')?.content.toLowerCase().includes('news') ||
  document.querySelector('meta[name="tags"]')?.content.toLowerCase().includes('news')
) {
  window.open("https://google.com/", "_self");
}

Oh, I didn’t mean automatic, I meant for intentional postprocessing done by a human with a designated tool.
I think that such postprocessing tools are often termed “code injection” or “hook” and in some sense we can postprocess any backend-created webpage with frontend JavaScript.

About the code example. Firstly, thanks a lot.
Secondly, it seems that there is an endless loop there on cnn.com @DaveMaxwell

How would a human-controlled tool be able to run before the page is rendered?

The point is that you cant tell the machine “dont do A”… AFTER IT HAS EVALUATED A.
You can tell it to undo what was done in A, yes.
You can make the value of A false before the check.
But unless you’ve got a way of stopping it mid-flow, you cant tell the machine “That thing you’ve already checked the value of, dont use that value.”

Actions in a script are not… parsed, put into a queue, and then executed at the end. That’s massive overhead for a process that may have no need for the queue.

Not to mention…

IF (A) THEN {B} ELSE IF (C) { PREVENT A }

fine… what if my previous line to that one is
IF (A) THEN (D)

… what is PREVENT A supposed to do? block both? block one? which one of these unassociated values in the queue are you supposed to stop? How does it know it’s supposed to go to the Else while A is true?

How does your computer based engine interpret this instruction?

VERSUS…

IF (A) THEN (D)
IF (A AND NOT C) THEN {B}

(Assume A is True)

Check A. Do D.
Check A. Check C. Skip B because C was true.

Everything moving forwards, everything able to be checked immediately and the appropriate action taken without needing to look backwards…

How would a human-controlled tool be able to run before the page is rendered?

I meant to something that comes between two stages (say, between parsing and rendering, perhaps).

IF (A) THEN {B} ELSE IF (C) { PREVENT A }

fine… what if my previous line to that one is
IF (A) THEN (D)

I have no significant knowledge about programming language development or formal logics so I could just say that D may not be able to run and an error would be thrown.

That’s… not how programming works.

if(A) { PREVENT C }
if(!C) { PREVENT A }

If A is true, C is made false;
but then C being false would prevent A… so C isnt false…so A wouldnt have been prevented…so it would…

Go into an infinite loop.

OR… you can just have straightforward logic that read command, execute command. read command, execute command.

Which do you think EVERY programming language is going to do?

So to get back to the actual question, rather than theoreticals about redesigning entire fundamental principles of computers…

This is because "https://cnn.com/" itself includes ‘cnn’. You’d need to add a second clause to make sure it isnt exactly cnn.com, or else rethink your logic here. Why is a URL containing cnn redirected to cnn?

Which do you think EVERY programming language is going to do?

I only know a little bit about JavaScript and even more little about Bash. I generally don’t know anything about any other of the hundreds of programming languages.

That’s… not how programming works.

Saying this on all or even most existing programming languages might be fair enough, but can you say that programming can never work like that by having middleprocessing? I can’t strictly determine that that it can’t.

  • For me, turning off JavaScript is one example to how we can exceptionally middleprocess a program (webpage) and running JavaScript on a parsed and rendered webpage is one example to how we can exceptionally postprocess a program (webpage).
  • I always wanted a PHP middleprocessing feature that would let me cancel the PHP-creation of some HTML structure by its PHP-given-CSS-class between PHP run AND parsing-rendering.
    Such middleprocessing feature would have saved me much time of studying and altering the core of a complex CMS like MediaWiki. In this case, deleting various commands spanning on several PHP files, which altogether create this CSS-classed data structure (and it was quite uniquely CSS-classed).

No, but I can say that if such a thing existed, it would require human level neuroprocessing to be parsed, and I would never ever write in that language, and I would never support anyone who does, because I can’t read their code and understand it.

If your code is 3000 lines long and at the end you write “PREVENT A”… go away. It’s like that mythical German book that’s 300 some odd pages and is one long runon sentence with a verb at the end that changes the entire meaning of the last 299 pages. Go away.

I think you are being too exreme about this because as you know libre programs are dyamic, not fixed like books and a programmer can legitimately desire a shortcut, mostly in personal modifications.