window.onbeforeunload may fire multiple times

…衆ロ難τιáo~ 提交于 2019-12-01 03:52:07

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);
};

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 ..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!