Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The right way to use <code>onbeforeunload</code> to confirm navigating away is to just return the string of the message you want to have shown. <a href="https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload" rel="nofollow">MDN has this to say</a>.</p> <blockquote> <p>The function should assign a string value to the returnValue property of the Event object and return the same string</p> </blockquote> <p>So your <code>onbeforeunload</code> function for the behavior you ask for would just be (same as binding it with jquery, especially since onbeforeunload does not support multiple event listeners like other events do)</p> <pre><code>window.onbeforeunload = function() { return "Are you sure?"; }; </code></pre> <p>But ironically, Firefox doesn't support this for security purposes.</p> <blockquote> <p>Note that in Firefox 4 and later the returned string is not displayed to the user. See <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=588292" rel="nofollow">bug 588292</a>.</p> </blockquote> <p><strong>Edit:</strong> I read more of the bug report. The main reason they site for this decision is: "1. Remove the site-supplied text, since this is a security issue (untrusted text in browser dialogs)". I wonder how they feel about an <code>alert</code>?</p> <p>Most modern browsers (Chome, IE 9+ or earlier, and Opera, I know for sure) will ignore anything you try to do in an <code>onbeforeunload</code> function other than returning a string for display. This is to prevent hijacking the users browser, opening popups, overriding navigation attempts by pointing the user another, possibly malicious domain, etc.</p> <p><strong>Edit 2:</strong> I was apparently incorrect. Only <em>some</em> things are disallowed in <code>onbeforeunload</code>, they just happen to mainly be the types of things you tried in your sample code, having to do with event propagation and page navigation. From <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=588292#c97" rel="nofollow">deep in the comments</a> of that FF bug report, user oyasumi posts a link to this jsFiddle with a work around for displaying custom text to FF 4+ users: <a href="http://jsfiddle.net/ecmanaut/hQ3AQ/" rel="nofollow">http://jsfiddle.net/ecmanaut/hQ3AQ/</a> So apparently calling <code>alert()</code> is still allowed, even in <code>onbeforeunload</code>, which hilariously is doing exactly what the was original reason for the 'bug' "fix": displaying custom text in a browser/application/OS/official-looking dialog.</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