stack
stack

Reputation: 10218

How can I detect back button in the browser?

I have a function named back() which will be used for ajax calls. Actually I have an array stack contains last 5 search results and that back function will switch to the previous result set (according to that array stack) and it even changes the URL using window.history.pushState() when you click on the back button.

That back button I was talking about, is an element inside the browser which revokes back() function. Now I want to revoke back() function also when user click on the back button of the browser. Something like this:

window.onhashchange = function() {
 back(); // this function also changes the url
}

But sadly window.onhashchange will be revokes twice when I click on the back of the browser. Because window.onhashchange will be revoked when you change the URL using window.history.pushState().

Anyway, how can I detect what things changes the URL? Either my JS code or the back button of the browser?

Upvotes: 3

Views: 2950

Answers (2)

Nikola Lukic
Nikola Lukic

Reputation: 4244

One of solution is to implement onunload event with localstorage option. This is from my head maybe you will need correction but this is base !

var history = [];

window.onload = function(){

  var handler;

  if ( localStorage.getItem('history') == null ) {
   // FIRST TIME
   history[0] = window.location.href;
   localStorage.setItem("history", JSON.stringify(history));
  }
  else {
   handler = localStorage.getItem('history');
   handler = JSON.parse(handler);
   history = handler;
   // Just compare now 
   if (history[history.length-1] == window.location.href) {
       // no change
   } else {
      history.push(window.location.href);     
   }

  }

}

window.onunload = function(){

   localStorage.setItem('history', JSON.stringify(history));

}

Note :

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

Upvotes: 1

Adelin
Adelin

Reputation: 8209

You can use performance.navigation.type

At any given point, for example on document.onload, you can read the value of type and, if it's:

  • 0 The page was accessed by following a link, a bookmark, a form submission, a script, or typing the URL in the address bar.
  • 1 The page was accessed by clicking the Reload button or via the Location.reload() method.
  • 2 The page was accessed by navigating into the history.
  • 255 any other way.

Just beware that support is limited according to the compatibilty table. However, from the looks of it, it seems the table is outdated. It says it is not supported on chrome and I just tested it and works as expected on my chrome version (67.0)

Upvotes: 4

Related Questions