Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't modify the default dialogue for <code>onbeforeunload</code>, so your best bet may be to work with it.</p> <pre><code>window.onbeforeunload = function() { return 'You have unsaved changes!'; } </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx" rel="noreferrer">Here's a reference</a> to this from Microsoft:</p> <blockquote> <p>When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.</p> </blockquote> <p>The problem seems to be:</p> <ol> <li>When <code>onbeforeunload</code> is called, it will take the return value of the handler as <code>window.event.returnValue</code>.</li> <li>It will then parse the return value as a string (unless it is null).</li> <li>Since <code>false</code> is parsed as a string, the dialogue box will fire, which will then pass an appropriate <code>true</code>/<code>false</code>.</li> </ol> <p>The result is, there doesn't seem to be a way of assigning <code>false</code> to <code>onbeforeunload</code> to prevent it from the default dialogue.</p> <p>Additional notes on jQuery:</p> <ul> <li>Setting the event in jQuery <strong>may</strong> be problematic, as that allows other <code>onbeforeunload</code> events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.</li> <li><p>jQuery doesn't have a shortcut for <code>onbeforeunload</code> so you'd have to use the generic <code>bind</code> syntax.</p> <pre><code>$(window).bind('beforeunload', function() {} ); </code></pre></li> </ul> <p><strong>Edit 09/04/2018</strong>: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: <a href="https://developers.google.com/web/updates/2016/04/chrome-51-deprecations#remove_custom_messages_in_onbeforeunload_dialogs" rel="noreferrer">release note</a>)</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