1

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();
 });
Gilbert V
  • 1,050
  • 5
  • 16
  • 43

1 Answers1

3

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?

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • So there is no way of getting it the way I want it to work then? Or of a real way to do something if cancel was pressed? – Gilbert V Sep 24 '12 at 18:45
  • Can the timeout binding work that way, in the article you shown me? – Gilbert V Sep 24 '12 at 18:53
  • 1
    @GilbertV correct, the only way you can tell if the navigation was cancelled is by running the `setTimeout`. – jbabey Sep 24 '12 at 18:58
  • Could you maybe provide a example of how I would wrote it into this I am not really familiar with setting it up and would be much appreciated. – Gilbert V Sep 24 '12 at 19:06
  • @GilbertV there is a code example in the accepted answer of the question i linked. – jbabey Sep 24 '12 at 19:11
  • Okay I updated the code on top to reflex the example but dont know if it is accurate. does it look right? – Gilbert V Sep 24 '12 at 19:18