[removed] may fire multiple times

后端 未结 2 1025
感动是毒
感动是毒 2021-01-12 02:00

Just because you don\'t see use for a feature doesn\'t mean it isn\'t useful.

The Stack Exchange network, GMail, Grooveshark, Yahoo! Mail, and Hotmail use the onbe

2条回答
  •  一个人的身影
    2021-01-12 02:30

    I have encapsulated the answers from above in an easy to use function:

    function registerUnload(msg, onunloadFunc) {
        var alreadPrompted = false,
            timeoutID = 0,
            reset = function() {
                alreadPrompted = false;
                timeoutID = 0;
            };
    
        if (msg || onunloadFunc) { // register
            window.onbeforeunload = function() {
                if (msg && !alreadPrompted) {
                    alreadPrompted = true;
                    timeoutID = setTimeout(reset, 100);
                    return msg;
                }
            };
    
            window.onunload = function() {
                clearTimeout(timeoutID);
                if (onunloadFunc) onunloadFunc();
            };
        } else { // unregister
            window.onbeforeunload = null;
            window.onunload = null;
        }
    }
    

    To register use:

    registerUnload("Leaving page", function() { /* unload work */ });
    

    To unregister use:

    registerUnload();
    

    Hope this helps ..

提交回复
热议问题