Detecting back

homeblogmastodonblueskythingiverse



I recently ran into a situation where I wanted a page to reload if the user reached it by pressing back. Firefox has the interesting feature that it remembers the full state of documents in the browser history, including any javascript variables, DOM manipulation, and timeouts. Firefox also utterly ignores any "cache-control" headers telling it not to cache when you press back.

Some solutions that failed:

My current best solution: Set an interval, detect periods where the interval handler is not called.

var NOW = null;
function check_timeslip() {
    var now = Date.now();
    if (NOW && now > NOW+5000) window.location.reload();    
    NOW = now;
}

setInterval(check_timeslip, 1000);

Obviously this is not 100% reliable.


Update: Matthew Mastracci pointed me to the Firefox specific pageshow and pagehide events. Firefox seems to be somewhat particular about how these events are set. The following works:

document.body.setAttribute('onpagehide', 'setTimeout("window.location.reload()", 0);');

IE6 can be forced to reload by adding Cache-Control: no-store to the response headers.


Update 2: Matthew suggests using the unload event. His full solution is as follows:

Content-Type: text/html
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

<html>
<body onunload='return false;'>
...



[æ]