Skip to content Skip to sidebar Skip to footer

How To Detect The Back Button

I've set up a page where I'm using the following code so when you click on a link the content and URL changes without refreshing: window.history.pushState('object or string', 'titl

Solution 1:

You can use onpopstate, like this. It will be fired when the navigation buttons are used, too.

http://jsfiddle.net/54LfW/4/

window.onpopstate = function(e) { // executed when using the back button for examplealert("Current location: " + location.href); // location.href is current locationvar data = e.state;
    if(data) {
        alert(JSON.stringify(e.state)); // additional data like your "object or string"
    }
};

Solution 2:

This answer is already given, but I will try to explain what I understand using pushState Consider your url is "google.com/gmail"

1.Make currentURL as temp URL, so your browser will show this URL. At this step, there will be one URL in the stack i.e google.com/gmail#!/tempURL.

history.replaceState(null, document.title, location.pathname+"#!/tempURL"); 

2.Push the previousURL as new state so now your browser will show previousURL i.e google.com/gmail.

history.pushState(null, document.title, location.pathname);

Current state of the stack


First element : google.com/gmail


Last element : google.com/gmail#!/tempURL


3.Now add listener to listen event

window.addEventListener("popstate", function() {
      if(location.hash === "#!/tempURL") {
        history.replaceState(null, document.title, location.pathname);
        //replaces first element of last element of stack with google.com/gmail so can be used furthersetTimeout(function(){
          location.replace("http://www.yahoo.com/");
        },0);
      }
    }, false);

Post a Comment for "How To Detect The Back Button"