官方定義
onbeforeunload 事件在即將離開當前頁面(刷新或關閉)時觸發。該事件可用於彈出對話框,提示用戶是繼續瀏覽頁面還是離開當前頁面。
使用場合
當我們界面中有未提交的表單,或者有未保存的文本內容,用戶點擊關閉按鈕,需要瀏覽器彈出提示框,就需要使用這個事件 onbeforeunload
調用方式
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '自定義文本';
});
// 當然,也可以通過以下方式調用:
window.onbeforeunload = function(event) {
...
};
或者在body標籤上綁定onbeforeunload,但更推薦使用addEventListener的方式調用。
HTML規範建議作者使用 Event.preventDefault() 而非 Event.returnValue 的方式來提示用戶。但是,該種方法還沒有得到全部瀏覽器的支持,所以需要配合使用。
React 中使用
在 React 中,需要在 DidMount 階段監聽這個事件,在 willunmount 階段釋放這個事件的回調函數。
componentDidMount() {
window.onbeforeunload = this.onbeforeunload;
}
componentWillUnmount() {
window.onbeforeunload = null;
}
onbeforeunload = () => {
// handle unsaved file
return '';
}
界面提示文本
當事件返回值不是null或者undefined時,用戶將會被提醒是否離開頁面。(但測試後發現即便返回null或者undefined,彈出框也會被展示)。
如果不需要展示彈窗,不使用 Event.preventDefault(),Event.returnValue即可。
returnValue自定義文本無效原因:在舊版本瀏覽器中,事件的返回值會被展示在對話框中。但從Firefox 44,Chrome 51,Opera 38,和Safari 9.1以後,返回文本將不會被展示,換言之,無法自定義彈窗提示文本。
默認的提示文本如下:
Firefox(66.0.3)“此頁面想詢問您是否要離開 - 您輸入的數據可能不會被保存”
Safari(10.1.2)“您確定要離開此頁面嗎?”
Chrome(74.0.3729.131)“重新加載此網站?”“系統可能不會保存您所做的更改。”
alert,confirm,prompt不執行
在一些瀏覽器中,在onbeforeunload中調用alert,confirm,prompt等方法會被忽略。
onbeforeunload無效
之前遇到的情況是,在chrome中onbeforeunload事件時而執行時而失效,以爲是瀏覽器的兼容問題,百思不得其解,但後來發現如下解釋:As of Chrome 60, the confirmation will be skipped if the user has not performed a gesture in the frame or page since it was loaded.在Chrome和Firefox中,頁面加載完成後,如果用戶未對頁面進行操作,比如“點擊”、“輸入”等等,onbeforeunload將不會被執行。而在Safari中onbeforeunload總是會被執行。需要指出的是,許多瀏覽器會忽略該事件並自動關閉頁面無需用戶的確認。火狐瀏覽器在配置頁面about:config設有一個dom.disable_beforeunload的開關變量用於開啓這個功能。
參考文檔
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/onbeforeunload
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
https://www.runoob.com/jsref/event-onbeforeunload.html
https://blog.csdn.net/u014259536/article/details/89888573