[javascript] Intercept page exit event

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 FF & Chrome also.

This question is related to javascript javascript-events internet-explorer

The answer is


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


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>

I have users who have not been completing all required data.

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
    <cfset unloadCheck=1>
    $("#myInput").change(function(){
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
    });
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    verify();
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to javascript-events

How to fire an event on class change using jQuery? how to toggle (hide/show) a table onClick of <a> tag in java script How to pass parameter to function using in addEventListener? Open popup and refresh parent page on close popup How to remove all listeners in an element? Destroy or remove a view in Backbone.js Add event handler for body.onload by javascript within <body> part How to trigger jQuery change event in code How can I trigger an onchange event manually? Intercept page exit event

Examples related to internet-explorer

Support for ES6 in Internet Explorer 11 The response content cannot be parsed because the Internet Explorer engine is not available, or Flexbox not working in Internet Explorer 11 IE and Edge fix for object-fit: cover; "Object doesn't support property or method 'find'" in IE How to make promises work in IE11 Angular 2 / 4 / 5 not working in IE11 Text in a flex container doesn't wrap in IE11 How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? includes() not working in all browsers