How do I stop a page from unloading (navigating away) in JS?

Solution 1:

onbeforeunload is the one you want; your function "should assign a string value to the returnValue property of the Event object and return the same string". Check the docs from Microsoft and Mozilla for details.

The string you return will be used by the browser to present the user with a custom confirm box, allowing them to refuse to stay there if they so choose. It has to be done that way to prevent malicious scripts causing a Denial-of-Browser attack.

Solution 2:

This code warns as per Natalie's suggestion, but disables the warning if a form on the page was submitted. Uses JQuery.

var warning = true;
window.onbeforeunload = function() { 
  if (warning) {
    return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
  }
}

$('form').submit(function() {
   window.onbeforeunload = null;
});

Solution 3:

you want to use the onbeforeunload event.