My web page has a countdown snippet which reads its remaining time from a hidden field. It count downs from 300 to 0 with a step of 1 second开发者_开发百科, and updates the hidden field consequently. When I reload the page, browser serves the old value of the hidden field rather that fetching it from the server.
The snippet is:
<span id="counter"> </span> <input type="hidden" id="remaining" value="300" />
I need to get the target URL of the page within an event listener block, such as:
$(window).unload(function() {
alert(window.location.destination); });
Of course, I made up the "destination" part. What I really need is to detect the reload, and attach a hash parameter to the URL to prevent caching.
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.
精彩评论