For work, I spend a lot of time on domain-specific forums. Throughout the day, I check those forums to see if there are any questions and answers relevant to what I am working on. However, the particular site I am using does not automatically update, and so I have to refresh it. This isn't that big of a deal, but I decided I would save the following JavaScript script as a bookmark:
setInterval(function() { document.location.reload(true); }, 1000);
Essentially, I wanted to force the page to reload every second. However, when it reloads it seems it causes my script to stop running, and so the only effect of my script is a single reload. It's no better than just refreshing the site by hand.
I suppose the more general question is "is there any way to keep a script running even when a user travels to a new site?" I'm guessing not, as then sites could track you as you browsed the rest of the internet. Still, it seems that there might be levels of script execution; perhaps executing a script from a bookmark is different than a <script> tag on a webpage; if I were a browser designer I would have taken that into account and treated is as "browser code" running behind the scenes independant of the currently loaded page. Is that the way browsers work, or does it see all scripts as just running on the currently loaded page?
Thanks!
Yep. Well, you have to think in terms of the Client-Server infrastructure. Anytime the browser reloads, it has to send a new request to the server which technically would kill all running JS processes within the current DOM. Which is why just using
setIntervalby itself would not work either because the process is killed and never carry over the new reload.Solution: You have to use User Scripts
In order to make this work, you would have to put your script within the context of the browser alone, not the Client-Server architecture. That way, since the context of execution is the Browser and not the DOM, a page refresh does not kill the JS process. The process is only killed when you close the Browser.
If you are using Chrome, check out the Chrome extension Tampermonkey I believe that is the best way to manage user scripts in the browser. Add your script by creating a New Script, save, then under the script settings, add your targeted site under the user matches
Limitation: This solution would work only for yourself (who can install extensions or add user script on your own browser) and not for other users of the website because we are outside of the Client-Server context.