Question

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();
 });
Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top