How do I detect if a user has got to a page using the back button?
Solution 1:
Use a hidden form. Form data is preserved (typically) in browsers when you reload or hit the back button to return to a page. The following goes in your page (probably near the bottom):
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
In your javascript, you will need the following:
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') window.location.reload();
function mark_page_dirty() {
dirty_bit.value = '1';
}
The js that sniffs the form has to execute after the html is fully parsed, but you could put both the form and the js inline at the top of the page (js second) if user latency is a serious concern.
Solution 2:
Here is a very easy modern solution to this old problem.
if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
alert('Got here using the browser "Back" or "Forward" button.');
}
window.performance is currently supported by all major browsers.
Solution 3:
This article explains it. See the code below: http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
<html>
<head>
<script>
function pageShown(evt){
if (evt.persisted) {
alert("pageshow event handler called. The page was just restored from the Page Cache (eg. From the Back button.");
} else {
alert("pageshow event handler called for the initial load. This is the same as the load event.");
}
}
function pageHidden(evt){
if (evt.persisted) {
alert("pagehide event handler called. The page was suspended and placed into the Page Cache.");
} else {
alert("pagehide event handler called for page destruction. This is the same as the unload event.");
}
}
window.addEventListener("pageshow", pageShown, false);
window.addEventListener("pagehide", pageHidden, false);
</script>
</head>
<body>
<a href="http://www.webkit.org/">Click for WebKit</a>
</body>
</html>