JS bookmarklet that will reload page every 60 seconds until x is true

Viewed 154

I'm trying to write a bookmarklet that will reload a page (Amazon delivery slots) every minute, and quit if certain conditions are met.

But how do I get the loop to continue after the reload? After the first reload, the loop is terminated.

1 Answers

Javascript execution does not persist across pageloads. If you run a bookmarklet, and then the page gets replaced, you will have a new page, without any of your custom Javascript running. A bookmarklet's execution cannot continue after the page has been reloaded.

I see 2 main options here:

  • Instead of replacing the page completely, just fetch the URL again via Javascript. Take the text response and parse it into a document with DOMParser, then examine the document for the element/conditions you want. (Won't work if the site's built-in Javascript is required to run for you to do your checks.)
  • Use a userscript instead of a bookmarket. Userscripts can execute automatically on pageload. Before reloading, set a persistent variable, such as a flag in sessionStorage. After reloading, at the beginning of the userscript, retrieve and check the flag - if it exists, then you're "in the loop", and you can perform the required checks and reload again after 60 seconds, if needed. Once the condition is met, clear the sessionStorage item so that it doesn't try to continue next time you happen to load the page. Only caveat is that you'd have to have a way to initialize the userscript - perhaps have it create a button on the page to start the loop.

The second method is what I'd choose. Userscripts are also a lot more maintainable than bookmarklets IMO.

(To write userscripts, install a userscript manager like Tampermonkey, press the "Create a new script" option on the page you want the script to run on, then type in the code you want to run on every pageload)

Related