在浏览器中检测后退按钮
我必须检测用户是否点击了后退按钮。
为此我使用
I have to detect if a user has clicked back button or not. For this I am using
window.onbeforeunload = function (e) {
}
如果用户点击后退按钮,则有效。但是,如果用户单击F5
或浏览器的重新加载按钮,也会触发此事件。我如何解决这个问题?
It works if a user clicks back button. But this event is also fired if a user click F5 or reload button of browser. How do I fix this?
就AJAX而言......
So as far as AJAX is concerned...
使用大多数使用AJAX导航页面特定部分的网络应用程序时向后按是一个巨大的问题。我不接受必须禁用按钮意味着你做错了什么,事实上,不同方面的开发人员长期遇到这个问题。这是我的解决方案:
Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
据我所知,这可以解决这个问题chrome,firefox,尚未测试IE 。
As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.