Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript window.onbeforeunload not working correctly
    text
    copied!<p><strong>UPDATE: <em>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</em></strong></p> <p>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</p> <p>I set it up on one page by adding this script code to the top of the view file</p> <pre><code>var saving = false; window.onbeforeunload = function(){ if(!saving) return 'Are you sure you don\'t want to save before you leave?'; }; </code></pre> <p>where saving is set to true if the user hits the save button, which redirects them to a separate page. </p> <p>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.</p> <p>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.</p> <p>So I currently have it set up as:</p> <pre><code>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(); } } } </code></pre> <p>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. </p> <p>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.</p> <p>Thanks,</p> <p>-Alan</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload