You can't get the URL of the page the user is going to in an unload
function, or at all (in some cases it would be a privacy risk). And a fragment identifier (hash) on the URL will not prevent caching; changing it will not even reload the page. For a cachebuster you would have to write to the ?query
part of the URL, which you could do through eg. location.search= '?'+Math.random();
.
But none of that is a good idea. The behaviour where browsers ‘remember’ the previous value of a form when reloading or going back/forwards onto a page is unwanted, so your best bet is simply not to use a form field at all. Have the script write out data in another part of the DOM:
<span id="counter" class="remaining-300"></span>
and read that from the span element's .className
in script, or simply write the variable straight to JS:
<span id="counter"></span>
<script type="text/javascript">
var remaining= 300;
</script>
This will reset the countdown to 300 seconds each time the page is loaded.
You might also need to think about the ‘bfcache’, which on many modern browsers retains your original page — including all the content and script state in it — when a user navigates away, then brings it back without reloading when you press ‘Back’.
Currently that will continue ticking the countdown, but it won't have ticked whilst the page was being hidden, so you'll have as much time left as you had when you left. If that's not what you want, you could try setting a deadline timeout independently of the ticker interval, to always fire at the expected reload time. Or, as a last resort and generally to be avoided, you can break the bfcache deliberately by setting onunload
to anything, even a function that does nothing.