Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confirm() on window.onbeforeunload

Tags:

javascript

I want to show a confirmation dialog if the user wants to leave the page with unsaved form data. What I have is:

window.onbeforeunload = function() {
    if (not_saved) if (confirm('Changes will not be saved')) return true;
    return false;
}

But no matter what the user clicks, the result is the same - the stupid hardcoded dialog box that asks them whether they want to leave the page or stay on page. What I want to ask them is whether they want to stay or leave, and if they want to stay nothing happens, if they want to leave, they leave. Is this even possible? I can see how browsers want to limit what websites can do about keeping the users on the page, but I think I've seen some websites (Google Docs I think) having nice civilized dialog boxes.

like image 671
DMIL Avatar asked Aug 26 '12 16:08

DMIL


1 Answers

window.onbeforeunload = function(e) {
    return 'Dialog text here.';
};

Docs:

  • https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
  • http://dev.w3.org/html5/spec-LC/history.html#unloading-documents

Note that in Firefox 4 and later the returned string is not displayed to the user.

If the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent should ask the user to confirm that they wish to unload the document. The prompt shown by the user agent may include the string of the returnValue attribute, or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display, for instance.)

like image 184
Peter Avatar answered Sep 22 '22 06:09

Peter