onbeforeunload and onunload getting one to work after the other

喜你入骨 提交于 2019-12-24 14:10:53

问题


I am having some trouble with the on before unload and the unload method. I thought i set the code right in terms of the onload method only firing up after the confirm method for onbeforeunload was set a true. but sadly that isn't the case, what is happening is the unload method is starting even if the onbeforeunload method is set to false and the person wants to stay at the website. Here is the code I am working on it has changed a lot since I started hope its okay. I am sure it isn't since its not working the way I want it to.

 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 does not work like you think it does. You can return a string from the handler, which will prompt a messsage, or undefined which will do nothing.

window.onbeforeunload = goodbye;

function goodbye(e) {
    if (!validNavigation) {
        return leave_message;
    } else {
        return undefined;
    }
}

Related: Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?



来源:https://stackoverflow.com/questions/12570800/onbeforeunload-and-onunload-getting-one-to-work-after-the-other

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