javascript計時器範例 - 檢測後退按鈕在瀏覽器中單擊
javascript碼表 (4)
這個問題在這裡已經有了答案:
我必須檢測用戶是否點擊了後退按鈕。 為此,我正在使用
window.onbeforeunload = function (e) {
}
如果用戶單擊後退按鈕,它可以工作。 但是,如果用戶單擊F5或重新加載瀏覽器按鈕,也會觸發此事件。 我該如何解決?
https://code.i-harness.com
我假設您正在嘗試處理Ajax導航,而不是試圖阻止您的用戶使用後退按鈕,這違反了有關UI開發的每一個原則。
這裡有一些可能的解決方案: JQuery History Salajax 一個更好的Ajax後退按鈕
我知道的最佳方式
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;
};
所以就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;
}
};
}
}
至於我已經能夠告訴這個工作跨chrome,firefox, 尚未測試IE 。
由於後退按鈕是瀏覽器的功能,因此可能很難更改默認功能。 雖然有一些工作。 看看這篇文章:
http://www.irt.org/script/311.htm
通常,需要禁用後退按鈕是編程問題/缺陷的良好指示。 我會尋找一種替代方法,比如設置會話變量或存儲表單是否已經提交的cookie。