Is there any way to detect if current page came from back button?
I want to load data from cookie only if current page came from back button.
You can check the document. readyState property. From MDN: Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.
For pages that are set as non-cached, the browser reloads the page from the server when you press Back, as though it was the first time you are visiting it. For cached pages, the browser displays it out of the cache, which is much faster.
You can simply fire the “popState” event in JQuery e.g: $(window). on('popstate', function(event) { alert("pop"); });
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.
.
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With