Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if page is load from back button

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.

like image 721
Valter Avatar asked Jun 15 '16 14:06

Valter


People also ask

How do you know if a page is fully loaded?

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.

What happens when browser Back button is pressed?

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.

How does JQuery handle browser back button?

You can simply fire the “popState” event in JQuery e.g: $(window). on('popstate', function(event) { alert("pop"); });


1 Answers

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> 
like image 177
Radderz Avatar answered Oct 14 '22 05:10

Radderz