fac*_*ook 73 javascript jquery
我必须检测用户是否点击了后退按钮.为此,我正在使用
window.onbeforeunload = function (e) {
}
Run Code Online (Sandbox Code Playgroud)
如果用户单击后退按钮,它可以工作.但是,如果用户单击F5或重新加载浏览器按钮,也会触发此事件.我该如何解决?
Gus*_*ord 63
所以就AJAX而言......
使用大多数使用AJAX的网络应用程序按回来浏览页面的特定部分是一个巨大的问题.我不接受"必须禁用按钮意味着你做错了什么",事实上,不同方面的开发人员长期遇到这个问题.这是我的解决方案:
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;
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
至于我已经能够告诉这个工作跨chrome,firefox,还没有测试IE.
Ben*_*uer 60
请尝试这个(如果浏览器不支持"onbeforeunload"):
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');
}
});
Run Code Online (Sandbox Code Playgroud)
小智 8
我知道的最佳方式
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;
};
Run Code Online (Sandbox Code Playgroud)
我通过这种方式检测后退按钮:
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.
};
}
Run Code Online (Sandbox Code Playgroud)
它可以工作但我必须在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);
}
};
Run Code Online (Sandbox Code Playgroud)
}
非常重要,history.pushState("jibberish", null, null);重复浏览器历史记录.
有人知道我能修复它吗?
我假设您正在尝试处理 Ajax 导航,而不是尝试阻止用户使用后退按钮,这几乎违反了 UI 开发的所有原则。
以下是一些可能的解决方案:
| 归档时间: |
|
| 查看次数: |
284795 次 |
| 最近记录: |