Dimitar Nestorov
Dimitar Nestorov

Reputation: 2604

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", "title", "/photo.php");

But when a user clicks on the back button the content doesn't change back. How to detect the back button?

Upvotes: 5

Views: 9852

Answers (2)

Shoaib Chikate
Shoaib Chikate

Reputation: 8975

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 further
        setTimeout(function(){
          location.replace("http://www.yahoo.com/");
        },0);
      }
    }, false);

Upvotes: 3

pimvdb
pimvdb

Reputation: 154818

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 example
    alert("Current location: " + location.href); // location.href is current location

    var data = e.state;
    if(data) {
        alert(JSON.stringify(e.state)); // additional data like your "object or string"
    }
};

Upvotes: 6

Related Questions