Fortunately, we don't have to support browsers below IE10, so if you're willing or privileged enough to support only browsers that are HTML5 capable, the following should work:
/*
* The following is intentional, to force Firefox to run
* this JS snippet after a history invoked back/forward navigation.
*/
window.onunload = function(){};
function formatTime(t) {
return t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds();
}
if (window.history.state != null && window.history.state.hasOwnProperty('historic')) {
if (window.history.state.historic == true) {
document.body.style.display = 'none';
console.log('I was here before at ' + formatTime(window.history.state.last_visit));
window.history.replaceState({historic: false}, '');
window.location.reload();
} else {
console.log('I was forced to reload, but WELCOME BACK!');
window.history.replaceState({
historic : true,
last_visit: new Date()
}, '');
}
} else {
console.log('This is my first visit to ' + window.location.pathname);
window.history.replaceState({
historic : true,
last_visit: new Date()
}, '');
}
Well, here's the code without comments and flab:
window.onunload = function(){};
if (window.history.state != null && window.history.state.hasOwnProperty('historic')) {
if (window.history.state.historic == true) {
document.body.style.display = 'none';
window.history.replaceState({historic: false}, '');
window.location.reload();
} else {
window.history.replaceState({historic : true}, '');
}
} else {
window.history.replaceState({historic : true}, '');
}
Stick that just before your closing body tag, and you'll have a fairly clean solution.
This will work with any combination of back/forward being clicked, and the moment the user lands on a new page, no forced reloading will occur.
Read more about the History object on MDN:
MDN - The History Object
MDN - Manupulating the Browser History