Detecting the Page Leave event in JavaScript

You may need to detect if the user is leaving your web page for displaying a warning message to the user mentioning that he may not leave the page and the form is containing data filled by him. To be able to detect this event in JavaScript, you need to deal with the "onbeforeunload" event. The following example explains the idea.

In this example, there is a simple form that contains an input text. When the user enters something in the input text, a warning message appears.

<HTML>
<HEAD>
	<TITLE>Welcome to the test Page</TITLE>
	<SCRIPT type="text/javascript">
		window.onbeforeunload = function(event) {
			
			if (hasData()) {
				return "You entered information in the page. Are you sure you want to leave now?"; // Very important
			}
		}
		
		function hasData() {
			var someThing = document.getElementById("someThing");
			
			if (someThing.value != "") {
				return true;
			}		
			
			return false;
		}
	</SCRIPT>
	
</HEAD>
<BODY>
	<H1>Welcome to the test page</H1>
	
	<FORM>
		<LABEL for="someThing">Enter something here:</LABEL>
		<INPUT type="text" id="someThing"/>
	</FORM>
</BODY>
</HTML>

The "onbeforeunload" event is called when the user tries to leave the page. As shown in the code, to display the interruption message "You entered information in the page. Are you sure you want to leave now?", you have to specify the interruption message in the return of the event. The interruption message is displayed as shown in the figure below.
IE Preview

This code works with me on IE, Firefox, and Safari. I wish that this tip can be useful for you.

This entry was posted in JavaScript and tagged , , , , , by Hazem Saleh. Bookmark the permalink.

About Hazem Saleh

Hazem Saleh has more than eleven years of experience in Cloud, Mobile and Open Source technologies. He worked as a software engineer, technical leader, application architect, and technical consultant for many clients around the world. He is an Apache PMC (Project Management Committee) member and a person who spent many years of his life writing open source software. Beside being the author of the "JavaScript Unit Testing" book, "JavaScript Mobile Application Development" book, "Pro JSF and HTML5" book and the co-author of the "Definitive guide to Apache MyFaces" book, Hazem is also an author of many technical articles, a developerWorks contributing author and a technical speaker in both local and international conferences such as ApacheCon North America, Geecon, JavaLand, JSFDays, CON-FESS Vienna and JavaOne. Hazem is an XIBMer, he worked in IBM for ten years. Now, He is working for Nickelodeon New York as a Mobile Architect. He is also an OpenGroup Master Certified Specialist.