检测浏览器中的后退按钮

我必须检测用户是否点击了返回按钮。 为此,我正在使用

window.onbeforeunload = function (e) {
}

如果用户单击“回退”按钮,它就会工作。但是如果用户单击 F5,也会触发此事件 或浏览器的重新载入按钮。我如何解决这个问题?

326001 次浏览

我假设您正在尝试处理 Ajax 导航,而不是试图阻止用户使用后退按钮,后退按钮几乎违反了 UI 开发的所有原则。

以下是一些可能的解决方案: JQuery 历史 萨拉贾克斯 一个更好的 Ajax 后退按钮

由于返回按钮是浏览器的一个功能,所以很难更改默认功能。不过还是有一些解决办法的。看看这篇文章:

Http://www.irt.org/script/311.htm

通常,需要禁用后退按钮是一个很好的编程问题/缺陷指示器。我会寻找一种替代方法,比如设置一个会话变量或存储表单是否已经提交的 cookie。

至于 AJAX..。

在使用大多数使用 AJAX 导航页面特定部分的 Web 应用程序时,按回是一个巨大的问题。我不认为“必须禁用按钮意味着你做错了什么”,事实上,不同方面的开发人员早就遇到了这个问题。我的解决办法是:

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

目前为止,我已经能够告诉这个工程跨铬,火狐,还没有测试 IE

我知道的最好的方式

         window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"


// For IE and Firefox
if (e) {
e.returnValue = msg;
}


// For Safari / chrome
return msg;
};

请尝试以下操作(如果浏览器不支持“ onbefore 卸载”) :

jQuery(document).ready(function($) {


if (window.history && window.history.pushState) {


$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];


if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});


window.history.pushState('forward', null, './#forward');
}


});

我通过这种方式检测到了后退按钮:

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

它工作,但我必须在 Chrome 中创建一个 cookie 来检测我在页面的第一时间,因为当我进入网页没有控制 Cookie,浏览器没有点击任何后退按钮的反向操作。

if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};

}

非常重要的是,history.pushState("jibberish", null, null);复制了浏览器的历史记录。

有人知道我能修好它吗?