Getting onBeforeUnload to work with a setTimeout

六月ゝ 毕业季﹏ 提交于 2019-12-11 07:55:13

问题


I am trying to get onbeforeunload to work with a set timer of sorts but I can't seem to get it to fire up when the return is in place. I am hoping it would work with a timer but for some reason the timer isn't working. Here is the code I am working and thank you for your help in looking at it much appreciated.

var validNavigation = false;

function wireUpEvents() {
    var leave_message = 'Leaving the page';

    jQuery(
        function goodbye() {
            jQuery(window).bind('onbeforeunload', function() {
                setTimeout(function() {
                    setTimeout(function() {
                        jQuery(document.body).css('background-color', 'red');
                    }, 10000);
                },1);

            return leave_message;
        });
    }); 

    function leave() {
        if(!validNavigation) {
            killSession();
        }
    }

    //set event handlers for the onbeforeunload and onunloan events
    window.onbeforeunload = goodbye;

    window.onunload=leave;
}

// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function () {
    wireUpEvents();
});

回答1:


onBeforeUnload doesn't work with setTimeout. After onBeforeUnload executes, onUnload will be triggered and the page will change. This happens before the setTimeout callback is called.



来源:https://stackoverflow.com/questions/12571705/getting-onbeforeunload-to-work-with-a-settimeout

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