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

JavascriptJqueryEvents

Javascript Problem Overview


Does anyone know how to stop a page from reloading or navigating away?

jQuery(function($) {

/* global on unload notification */
warning = true;

if(warning) {
	$(window).bind("unload", function() { 
		if (confirm("Do you want to leave this page") == true) {
			//they pressed OK
			alert('ok');
		} else {
			// they pressed Cancel
			alert('cancel');
			return false;
		}
	});
}

});

I am working on an e-commerce site at the moment, the page that displays your future orders has the ability to alter the quantities of items ordered using +/- buttons. Changing the quantities this way this doesn't actually change the order itself, they have to press confirm and therefore committing a positive action to change the order.

However if they have changed the quantities and navigate away from the page I would like to warn them they are doing so in case this is an accident, as the changed quantities will be lost if they navigate away or refresh the page.

In the code above I am using a global variable which will be false by default (its only true for testing), when a quantity is changed I will update this variable to be true, and when they confirm the changes I will set it to false.

If warning is true and the page is unloaded, I offer them a confirmation box, if they say no they would like to stay on this page I need to stop it from unloading. return false isn't working, it still lets the user navigate away (the alerts are there for debugging only)

Any ideas?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

you want to use the onbeforeunload event.

Solution 4 - 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?";
}

Solution 5 - Javascript

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`;
  }
}

Isn't supported in chrome, safari and opera

Solution 6 - Javascript

As said in this comment, nothing in jQuery binds to the beforeunload event.

> @karim79: no it doesn't. There isn't anything in jQuery that binds to the beforeunload function; "unload" binds to the "unload" event. Search the source if you don't believe me ;-) – NickFitz

So you have to use pure Javascript to bind a function to the beforeunload event.

var warning = true;
$("form").submit(function() {
  warning = false;
});
$('#exit').click(function() {
  window.location.replace('https://stacksnippets.net/js')
});
window.onbeforeunload = function() {
  if(warning) {
    return true;
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form>
<input type="submit">
</form>

Solution 7 - Javascript

Try using e.preventDefault() instead of returning false. 'e' would be the first argument to your unload callback.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNatalie DowneView Question on Stackoverflow
Solution 1 - JavascriptNickFitzView Answer on Stackoverflow
Solution 2 - JavascriptcrafterView Answer on Stackoverflow
Solution 3 - JavascriptscunliffeView Answer on Stackoverflow
Solution 4 - JavascriptVIKRANT SHARMAView Answer on Stackoverflow
Solution 5 - JavascriptRitesh SView Answer on Stackoverflow
Solution 6 - JavascriptJustin LiuView Answer on Stackoverflow
Solution 7 - JavascriptNSSecView Answer on Stackoverflow