When a page is exiting or unloading, the ‘unload‘ event will be activate, however, this event can not stop a page from exit.

$(window).bind('unload', function(){});

Since jQuery 1.4, you can bind the ‘beforeunload‘ event to $(windows) object to stop a page from exit , unload or navigating away.

$(window).bind('beforeunload', function(){ 
	return '';
});

With ‘beforeunload‘ event attached, when you close the page, hits the back button or reload the page, a confirmation box will prompt to ask you whether you really want to go, choose ok to exit the page: cancel to stop the page from exit and stay on the same page.

In addition, you are allow to add your own message inside the confirmation box :

$(window).bind('beforeunload', function(){
	return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});

P.S The ‘beforeunload’ event is supported since jQuery 1.4

Try it yourself

<html>
<head>
<title>Refresh a page in jQuery</title>
 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 
</head>
 
<body>
 
<h1>Stop a page from exit with jQuery</h1>
 
<button id="reload">Refresh a Page in jQuery</button>
 
<script type="text/javascript">
 
	$('#reload').click(function() {
 
	 	location.reload();
 
	});
 
	$(window).bind('beforeunload', function(){
		return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
	});
 
</script>
 
</body>
</html>
Tags :
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus.
Here are some of my recommended Books

Related Posts

Popular Posts