In many case, but espeically in single-page applications when there is some unsaved data in the browser you might want to make sure the user does not accidently leave the page without first saving the data. This can be achived using the onbeforeunload (read "on before unload") event.

This even will trigger whenever the user is trying to leave the page by

  • clicking the "Back" button
  • reloading the page
  • typing in a new URL
  • clicking on a link on your page
  • or even when trying to close the current tab or the whole browser

In the following example, that you can try by clicking on the "Try" link, you can see how it is implemented.


<h1 id="home">Warn before leaving the page</h1>

// Warning before leaving the page (back button, or outgoinglink)
window.onbeforeunload = function() {
   return "Do you really want to leave our brilliant application?";
   //if we return nothing here (just calling return;) then there will be no pop-up question at all

<a href="">Code Maven</a>


We just need to assign a function to the window.onbeforeunload attribute and that function needs to return something. That will tell the browser that it should display a pop-up window asking the user if she wants to leave the page.

Firefox will just ask This page is asking you to confirm that you want to leave - data you have entered may not be saved..

Chrome will be more specific "Confirm Reload" + "Are you sure you want to reload this page?",

or "Confirm Navigation" + "Are you sure you want to leave this page?"

It will even include the text we returned from the function.

Safari will ask "Are you sure you want to leave this page?" and include our text.

Opera totally disregarded the code. I wonder if it would work if the JavaScript code was in a separate file.

If the function does not call return and just falls out at the end of the function, or if it calls return; without returning any value then the the browser will not ask anything and it will just do whatever we told it to do. (Reload the page, navigate away, etc.)

This allows us write some conditional code that will only show the popup of there is any data that needs saving.

window.onbeforeunload = function() {
   if (data_needs_saving()) {
       return "Do you really want to leave our brilliant application?";
   } else {