Confirmation on Leaving the Current Page in JavaScript

There are some places when you have to ask the user for confirmation when they leave the current page. This article shows you have to implement it.

I noticed a new feature in Gmail - the browser will ask the user to confirm exit if the user leaves in the middle on an operation. If you want to see this in action, just delete an email and close the window quickly. If you are fast enough, you will see this message...

You can use this code to implement this feature on your page.

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;

This code basically cancels the page exit action. The browser intercepts the attempt to cancel the page exit. I don't think this is in the JavaScript specifications - but its still a good thing. Otherwise, spammers can make it very hard for people to leave their page. Another reason why its a good thing is because its implemented in both IE and Firefox in a very similar way. So you don't need any coding gymnastics to use this feature.

Comments

Danesh Uthuranga at 31 Mar, 2008 01:08
Thank you very much for this service.
I was searching for this code..

Great work

Dan
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.