简体   繁体   中英

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?

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"
    }
};

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 ie 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 ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM