How to cancel a window unload?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gregerly
    Recognized Expert New Member
    • Sep 2006
    • 192

    How to cancel a window unload?

    I'm working on a corporate intranet site and am trying to create a page that will warn a user on window unload if they have not saved thier work. Basically I just select all inputs, and on change, set var changes = true; On window unload if changes==true, they have made changes that are not yet saved, and I want a confirm box to pop up, asking if they really want to leave or stay on the page? At this point is it to late to cancel the window unload? My code is below:

    [CODE=javascript]window.onunload =checkChanges;
    var changes=false;

    function checkChanges(){
    if(changes==tru e){//changes have been made
    if(!confirm("Do you want to leave without saving your changes?\n\nOK to Go, Cancel to stay on this page.")){
    window.unload=f alse;
    }
    }
    }

    //while looping thru all inputs
    inputs[x].onchange=funct ion(){
    changes=true;
    };[/CODE]

    I'm getting the proper confirm boxes, but I dont' know how to cancel the unload, if it's even possible.

    Thanks,

    Greg
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    try onbeforeunload.
    [CODE="javascrip t"]window.onbefore unload= function(){
    return 'You are about to leave this page, OK?';
    };[/CODE]

    Comment

    • gregerly
      Recognized Expert New Member
      • Sep 2006
      • 192

      #3
      Originally posted by mrhoo
      try onbeforeunload.
      [CODE="javascrip t"]window.onbefore unload= function(){
      return 'You are about to leave this page, OK?';
      };[/CODE]
      Thanks alot mrhoo. That worked great. I had some other questions, but I just got it figued out. Apparently the onbeforeunload prompts with it's own confirm that will keep a user on the page. Found that in this thread.

      Thanks again!

      Comment

      Working...