Javascript window.onbeforeunload not working correctly

javascriptonbeforeunload

UPDATE: there is something going on with the page I am trying to have the onbeforeunload work on. I set it up in the layout and it pops up for every page besides that one… So there has to be some broken javascript, or a javascript file that redefines onbeforeunload. Since it can only be defined once

I am working on a Rails project and I am setting up a pop up to alert the user that their data will be lost if they leave the page without saving. So I am using window.onbeforeunload

I set it up on one page by adding this script code to the top of the view file

var saving = false;

window.onbeforeunload = function(){
    if(!saving)
      return 'Are you sure you don\'t want to save before you leave?';
};

where saving is set to true if the user hits the save button, which redirects them to a separate page.

The problem is coming up when I try to set up the EXACT same thing on a separate view file, that also needs the same functionality.

Except when I drop the code above into the file no pop up is given, at all… at any point. So then I looked around at other available options to set up the onbeforeunload function.

So I currently have it set up as:

var saving = false;

window.onbeforeunload = displayConfirm();

function displayConfirm(){
    if(!saving){
      if(confirm('If you leave without saving, your changes will be lost. Press cancel to go back to save')){
        confirmExit();
      }
    }
}

on the second page. My issue is the pop up here doesn't work the same as the first implementation. Even weirder, the pop up shows up on window load… NOT before window unload.

I have been looking around and messing around with this for a few hours now. I am starting to get really irritated since this should have been an easy addition. Seeing as how it is already set up on a separate page, and working correctly. Any insight onto what maybe going wrong, or if I am making a stupid mistake, would be greatly appreciated.

Thanks,

-Alan

Best Answer

1) window.onbeforeunload = displayConfirm(); -- you're firing the function, instead of assigning it

2) onbeforeunload is great, but it's unsupported in a lot of ways. Some browsers don't even have it, period (all but the most recent Opera, for example), so if you're doing this for a wide audience, or you need it to work 100% cross-browser, onbeforeunload is sadly not enough on its own.