單頁應用裡,使用者按瀏覽器上一頁往往離開的是「站內某個區塊」,而不是真的想跳去別的網站。若能在即將離開時攔一下、給個確認或提示,體驗會好很多。這件事靠 popstate 事件搭配 History API 就能做到。
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 isn't supported. "
+ "You are leaving this application on next clicking the back button");
}
}
});
window.history.pushState('forward', null, './#forward');
}
});
關鍵是最後那行 pushState。它在歷史紀錄中「塞入一個新的一格」,而這一格的內容與目前頁面幾乎一樣。於是當使用者按上一頁時,瀏覽器只是回到這個影子項目,頁面並不會真正跳走,popstate 事件在此時觸發,我們就有機會攔住並提示。再按一次,才會真的離開。
外層的 if (window.history && window.history.pushState) 是能力偵測,避免在舊瀏覽器上丟出錯誤。
window.addEventListener('beforeunload', function (e) { e.preventDefault(); e.returnValue = ''; })。它會跳出瀏覽器原生的確認對話框,訊息文字由瀏覽器決定,無法自訂。popstate 裡適時消耗掉。