JavaScript before leaving the page

JavascriptJquery

Javascript Problem Overview


I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload

<script type="text/javascript">
function con() {
	var answer = confirm("do you want to check our other products")
	if (answer){
		
		alert("bye");
	}
	else{
		window.location = "http://www.example.com";
	}
}
</script>
</head>

<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>

But it confirm after page already closed? How to do it properly?

It would be even better if someone shows how to do it with jQuery?

Javascript Solutions


Solution 1 - Javascript

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

If you want to show a prompt before the user leaves the page, use onbeforeunload:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Or with jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    alert('Bye.');
}

Or with jQuery:

$(window).unload(function(){
  alert('Bye.');
});

Solution 2 - Javascript

This code when you also detect form state changed or not.

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

Solution 3 - Javascript

This what I did to show the confirmation message just when I have unsaved data

window.onbeforeunload = function() {
  if (isDirty) {
    return 'There is unsaved data.';
  }
  return undefined;
}

returning undefined will disable the confirmation

Note: returning null will not work with IE

Also you can use undefined to disable the confirmation

window.onbeforeunload = undefined;

Solution 4 - Javascript

This will alert on leaving current page

<script type='text/javascript'>
function goodbye(e) {
	if(!e) e = window.event;
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

	//e.stopPropagation works in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
}
window.onbeforeunload=goodbye; 

</script>

Solution 5 - Javascript

In order to have a popop with Chrome 14+, you need to do the following :

jQuery(window).bind('beforeunload', function(){
	return 'my text';
});

The user will be asked if he want to stay or leave.

Solution 6 - Javascript

You can use the following one-liner to always ask the user before leaving the page.

window.onbeforeunload = s => "";

To ask the user when something on the page has been modified, see this answer.

Solution 7 - Javascript

Most of the solutions here did not work for me so I used the one found here

I also added a variable to allow the confirm box or not

window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
	if (!hideWarning) {
		event.preventDefault();
		event.returnValue = '';
	}

});

Solution 8 - Javascript

Normally you want to show this message, when the user has made changes in a form, but they are not saved.

Take this approach to show a message, only when the user has changed something

var form = $('#your-form'),
  original = form.serialize()

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

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}

Solution 9 - Javascript

<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">

<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
      
<script>
function myFunction() {
    return "Write something clever here...";
}
</script>

</body>
</html>

https://www.w3schools.com/tags/ev_onbeforeunload.asp

Solution 10 - Javascript

Just a bit more helpful, enable and disable

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

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
Questionkd7View Question on Stackoverflow
Solution 1 - JavascriptRocket HazmatView Answer on Stackoverflow
Solution 2 - JavascriptWasim A.View Answer on Stackoverflow
Solution 3 - JavascriptMina MattaView Answer on Stackoverflow
Solution 4 - JavascriptAjit SinghView Answer on Stackoverflow
Solution 5 - JavascriptDavid BélangerView Answer on Stackoverflow
Solution 6 - Javascriptspencer.smView Answer on Stackoverflow
Solution 7 - JavascriptRaj Nandan SharmaView Answer on Stackoverflow
Solution 8 - JavascriptSimon FranzenView Answer on Stackoverflow
Solution 9 - JavascriptEmir MamashovView Answer on Stackoverflow
Solution 10 - Javascriptl2aelbaView Answer on Stackoverflow