2008-12-06 02:18

離開頁面前的對話匡 window.onBeforeUnload 事件

在頁面改變前會觸發 window.onBeforeUnload 事件
但要怎麼產生出離開前的確認匡呢?
根據在 MSDN(onbeforeunload Event) 找到的說明
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

我們只要對這個事件 return 一個訊息就可以達成
除了 undefined 以外的所有值都會產生確認匡

那到底要怎麼做呢?
/*註冊事件*/
window.onbeforeunload = function(){
    return "是否要離開此頁面";
};

/*解除事件*/
window.onbeforeunload = null;


就這樣簡單的幾行就可以達成
真是簡單到不行
而且大多數的瀏覽器都支援

展示頁面(Demo Page)

1 回應:

匿名 提到...

謝謝啦