[英]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:我已经设置了一个页面,我在其中使用以下代码,因此当您单击链接时,内容和 URL 会更改而不刷新:
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.您可以像这样使用
onpopstate
。 It will be fired when the navigation buttons are used, too.当使用导航按钮时,它也会被触发。
http://jsfiddle.net/54LfW/4/ 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"这个答案已经给出,但我会尝试解释我使用 pushState 的理解考虑你的 url 是“google.com/gmail”
1.Make currentURL as temp URL, so your browser will show this URL. 1.将 currentURL 设为临时 URL,这样你的浏览器就会显示这个 URL。 At this step, there will be one URL in the stack ie
google.com/gmail#!/tempURL
.在这一步,堆栈中将有一个 URL,即
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
. 2.Push the previousURL 作为新状态,所以现在你的浏览器将显示 previousURL 即
google.com/gmail
。
history.pushState(null, document.title, location.pathname);
Current state of the stack堆栈的当前状态
First element : google.com/gmail第一个元素: google.com/gmail
Last element : google.com/gmail#!/tempURL最后一个元素: google.com/gmail#!/tempURL
3.Now add listener to listen event 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.