如何检测浏览器的返回按钮?

5

我已经设置了一个页面,在该页面中使用以下代码,当您单击链接时,内容和URL会更改而无需刷新:

window.history.pushState("object or string", "title", "/photo.php");

但是,当用户点击“返回”按钮时,内容不会改变回来。如何检测后退按钮?


这个问题应该提供答案:https://dev59.com/p2w15IYBdhLWcg3w1_YN - thomasfedb
Opera浏览器不会发送onbeforeunload事件。 - Dimitar Nestorov
看看Ben Alman的JQuery BBQ。BBQ代表后退按钮和查询库。http://benalman.com/projects/jquery-bbq-plugin/ - Cory Kendall
@Dimitar 也许你应该这样做,这会消除一些问题。如果你反对这个建议,请在你的问题中明确说明。 - thomasfedb
2个回答

6
你可以像这样使用onpopstate,即使在导航按钮被使用时也会触发它。 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"
    }
};

3
这个问题的答案已经有了,但我会尝试解释一下我理解的pushState的使用方法。 假设你的URL是"google.com/gmail"。
1.将当前的URL设置为临时URL,这样浏览器就会显示这个URL。此时,在堆栈中只有一个URL,即google.com/gmail#!/tempURL
history.replaceState(null, document.title, location.pathname+"#!/tempURL"); 

2. 将上一个URL作为新状态推入,因此您的浏览器将显示上一个URL,即google.com/gmail

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

堆栈的当前状态


第一个元素: google.com/gmail


最后一个元素: google.com/gmail#!/tempURL


3.现在添加监听器以监听事件

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接