[removed] may fire multiple times

后端 未结 2 1003
感动是毒
感动是毒 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:24

    I think you could accomplish this with a timer (setInterval) that starts in the onbeforeunload callback. Javascript execution will be paused while the confirm dialog is up, then if the user cancels out the timed function could reset the alreadyPrompted variable back to false, and clear the interval.

    Just an idea.

    Ok I did a quick test based on your comment.

    <span id="counter">0</span>
    window.onbeforeunload = function () {
       setInterval(function () { $('#counter').html(++counter); }, 1);
       return "are you sure?";
    }
    window.onunload = function () { alert($('#counter').html()) };
    

    In between the two callbacks #counter never got higher than 2 (ms). It seems like using these two callbacks in conjunction gives you what you need.

    EDIT - answer to comment:

    Close. This is what i was thinking

    var promptBeforeLeaving = true,
        alreadPrompted = false,
        timeoutID = 0,
        reset = function () {
            alreadPrompted = false;
            timeoutID = 0;
        };
    
    window.onbeforeunload = function () {
        if (promptBeforeLeaving && !alreadPrompted) {
            alreadPrompted = true;
            timeoutID = setTimeout(reset, 100);
            return "Changes have been made to this page.";
        }
    };
    
    window.onunload = function () {
        clearTimeout(timeoutID);
    };
    
    0 讨论(0)
  • 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 ..

    0 讨论(0)
提交回复
热议问题