[英]How to detect the back button
我已经设置了一个页面,我在其中使用以下代码,因此当您单击链接时,内容和 URL 会更改而不刷新:
window.history.pushState("object or string", "title", "/photo.php");
但是当用户点击后退按钮时,内容不会变回去。 如何检测后退按钮?
您可以像这样使用onpopstate
。 当使用导航按钮时,它也会被触发。
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"
}
};
这个答案已经给出,但我会尝试解释我使用 pushState 的理解考虑你的 url 是“google.com/gmail”
1.将 currentURL 设为临时 URL,这样你的浏览器就会显示这个 URL。 在这一步,堆栈中将有一个 URL,即google.com/gmail#!/tempURL
。
history.replaceState(null, document.title, location.pathname+"#!/tempURL");
2.Push the previousURL 作为新状态,所以现在你的浏览器将显示 previousURL 即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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.