Note: This is reported to no longer work in the latest versions of Chrome.
When a user goes back a page, any visible form data is preserved, while any JavaScript variables are reset. I say ‘visible’ form data, as hidden fields seem not to be preserved, but invisible inputs are.
You can use this to your advantage in order to detect whether the page was an initial load, or had already been loaded previously such as from a back button click.
Create a invisible input field (not type ‘hidden’) with a value of ‘0’, and within a DOM ready loader check to see if the value has been set to ‘1’; if it has you know the page has already been loaded, such as from a back button; if it is still ‘0’ then the page has initially loaded for the first time, set the value to ‘1’.
Note: This is a bit delicate in the way it works, and probably doesn’t work in all browsers; I built it with Chrome in mind.
- The DOM needs to be loaded; not all ready functions work. The one
below does, so does the JQuery ready; however (function() { }) in my instance does not. - The Input cannot be of type=”hidden”. Set style=”display:none;”
on the input instead.
.
<input id="backbuttonstate" type="text" value="0" style="display:none;" />
<script>
document.addEventListener('DOMContentLoaded', function () {
var ibackbutton = document.getElementById("backbuttonstate");
if (ibackbutton.value == "0") {
// Page has been loaded for the first time - Set marker
ibackbutton.value = "1";
alert('First time load');
} else {
// Back button has been fired.. Do Something different..
alert('Previously loaded - Returned from Back button');
}
}, false);
</script>