Intercept page exit event

156,863

Solution 1

Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Solution 2

See this article. The feature you are looking for is the onbeforeunload

sample code:

  <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

Solution 3

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

Share:
156,863
Chris Ballance
Author by

Chris Ballance

Senior Engineering manager at Mark43 Señor Software Developer at Diligent Microsoft Alumni Code to Share Photographer BSC, MCP, CSM@ballancefacebookstudent

Updated on July 09, 2021

Comments

  • Chris Ballance
    Chris Ballance almost 3 years

    When editing a page within my system, a user might decide to navigate to another website and in doing so could lose all the edits they have not saved.

    I would like to intercept any attempt to go to another page and prompt the user to be sure they want this to happen since they could potentially lose their current work.

    Gmail does this in a very similar way. For example, compose a new email, start typing into the message body and enter a new location in the address bar (say twitter.com or something). It will prompt asking "Are you sure?"

    Ideas how to replicate this? I'm targeting IE8, but would like to be compatible with Firefox and Chrome also.

  • Chris Ballance
    Chris Ballance over 12 years
    I like this alternative to the popup. Thanks for the suggestion, Remi.
  • fmsf
    fmsf almost 12 years
    that doesn't make absolutely no sense -1. javascript is not threaded what you are doing is doing a postRequest and then pausing the computation of the site without allowing no one to do nothing (including your postRequest, that meanwhile was already sent before the computation pause).
  • Remi
    Remi almost 12 years
    And that is exactly why it works: indeed the post-request was send before the computation pause, but this little blocking of the page before it is actually left assures enough time for the browser client (not javascript) to really finish sending this request properly. I noticed that when I only send the request (without blocking) and leave the page immediately after, the request is not always send.
  • mtmurdock
    mtmurdock almost 12 years
    Could you explain the first line (var message = ...)? I dont know what that comma and the second expression is doing.
  • framp
    framp over 11 years
    I wouldn't use that in production. console.log is not crossbrowser; each postRequest suffers from the delay of the previous ones (which also means the page will hang there for the duration of your loop * scheduled requests); the requests aren't started in parallel; you aren't guaranteed to really send your requests. If I were forced to confront with this problem, I'd go with a synchronous ajax request, if there is only one request. With multiple requests I'd use async ajax requests and a loop which checks results (either success or error) from callbacks of the requests.
  • Remi
    Remi over 11 years
    I did not know that console.log is not cross-browser and a Synchronous Ajax request should indeed be the preferred solution (for a single request). The mentioned SCHEDULED_REQUEST is an object that acumulates any non-urgent information that should be send to the server, like a buffer of data, effectively joining multiple requests to one (of course the url of these requests is the same). Using a Synchronous Ajax request before unload should solve the problem cross-browser as you said. Thanks for your valuable comment!
  • T Nguyen
    T Nguyen over 11 years
    @mtmurdock That's just Javascript syntax to declare multiple variables. var foo, bar; is the same as var foo; var bar;
  • T Nguyen
    T Nguyen over 11 years
    @mtmurdock, The second statement "var e = e || window.event;" means set e equal to the parameter e (if it's truthy) or window.event if not truthy. It will not be truthy if the parameter e is null.
  • George Norberg
    George Norberg almost 10 years
    Saved the day, thought this might take me all day. New to Client side and didnt know of the onbeforeunload function! Thanks!
  • Shilpa Soni
    Shilpa Soni about 8 years
    Is there any way to identify that user has opted the "Leave this page" option rather than "Stay on this page"?
  • Eli Grey
    Eli Grey over 7 years
    @Blieque addEventListener isn't supported in IE8. Don't edit people's answers without even reading the question.
  • Blieque
    Blieque over 7 years
    @EliGrey Sorry, my mistake. I've submitted a different change that uses EventTarget.attachEvent for IE. I maintain that events should not be bound with assignment.
  • Micha Schwab
    Micha Schwab almost 7 years
    Doesn't work any more in Chrome (deprecated): developers.google.com/web/updates/2016/04/…
  • Mfoo
    Mfoo about 6 years
    @fmsf holy grammar !!
  • scipilot
    scipilot about 4 years
    @MichaSchwab it does still work but you just cannot specify the message displayed anymore to prevent scams. In Chrome 81 it says "Leave Site? Changes that you made may not be saved. [Cancel] [Leave]"
  • scipilot
    scipilot about 4 years
    But then the user cannot cancel, and discard the changes.
  • scipilot
    scipilot about 4 years
    @ShilpaSoni you would shortly get a subsequent unload event, developer.mozilla.org/en-US/docs/Web/API/Window/unload_event but I don't think there's a synchronous way.
  • scipilot
    scipilot about 4 years
    Before a page-reload the Chrome preset dialogue is similar but with "Reload" instead of "Leave" in the title and button.