confirm() on [removed]

前端 未结 3 670
广开言路
广开言路 2020-12-01 22:11

I want to show a confirmation dialog if the user wants to leave the page with unsaved form data. What I have is:

window.onbeforeunload = function() {
    if          


        
3条回答
  •  误落风尘
    2020-12-01 22:34

    Although window.onbeforeunload works, it's considered bad practice. It's better to use something like the following:

    if (typeof window.addEventListener === 'undefined') {
        window.addEventListener = function(e, callback) {
            return window.attachEvent('on' + e, callback);
        }
    }
    
    window.addEventListener('beforeunload', function() {
        return 'Dialog Text Here';
    });
    

    First we check if window.addEventListener exists, which it does not in IE, else we polyfill it, and then we attach the event.

提交回复
热议问题