How to make a JavaScript code which failed to run one webpage to run anyway on any other webpage?

There is a JavaScript code I want to run on a particular group of webpages – webpages that their URL includes the term layout.

I have tried this:

window.setInterval( () => {
    if (window.location.href.includes('layout')) {
        document.querySelector('.x').style.width = "600px";
    }
}, 1000);

This doesn’t really help because in general, until I get to any such webpage with a URL that does include the term layout, I have to visit several webpages which their URL does not include the term layout, hence this code will fail.
The code will succeed if I started my web browsing in a webpage that its URL includes the term layout but as I have just inclined, in general, that is not the case.
Therefore, I need a way to make this code to keep running even if it failed, that is, even if the if statement wasn’t met.
Is this even possible with the latest release of JavaScript and if so, how?

Remove the if statement then? Your question doesn’t really make much sense.

Is this for a browser extension? Normal JavaScript doesn’t persist across different pages.

I think that an if statement is good if we want to limit a code just for a certain group of webpages.

It’s not for a browser extension, it’s for a JS file of a content management system (Drupal).
In that JS file, there is other unrelated JS code underneath the code that I have presented here and I don’t want that an error about the code that I have presented here would “break” the running of all JS code underneath it.

I have just tested the code without the if statement and after placing it in the end of the JS file.

// Upper JS comes here

window.setInterval(()=>{
        document.querySelector('#drupal-off-canvas-wrapper').style.width = "600px";
}, 1);

It still doesn’t work, while the upper JS in the file does work.

Maybe because it’s a content management system (Drupal), something is clashing with something, hence I ask how to perhaps “isolate” this particular code to ensure that nothing is clashing with it?

if youve got access to put code into the page, why not just implement this css style change with… yaknow… css?

2 Likes

Oh, because the CSS didn’t work either:

#drupal-off-canvas-wrapper {
    width: 600px !important;
}

It might have to do with the fact that I try to change a JS-created popup.

More information here.

There appears to be some overlap here with a more recent thread from you

So as to avoid confusion, I am going to be closing this thread.

3 Likes