Confirmation on close when user closes tab/browser in ASP.Net

Link... on the 8th day of January, 2013

In the past, in my project about web application, there is requirement from user to show confirmation on close when user closes tab/browser of the application. It is like in gmail or facebook when you compose an email, you forget or close tab/browser without send email or submit your post. An confirmation will be shown to you.

There are some ways to make this, from the simple want up to the more complex. If you using ASP.NET or C#, you can put this script in masterpage or in a page. Please put this script in javascript area in your page.

Method 1:
var warnMessage = “Are you sure want to close Application?”;
$(window).load(function () {
$(window).bind(‘beforeunload’, function () { return warnMessage; })
});

Method 2:
var warnMessage = “Are you sure want to close Application?”;
$(‘input:not(:button,:submit),textarea,select’).live(“change”, function () {
window.onbeforeunload = function () { return warnMessage };
});

Method 3:
var warnMessage = “Are sure you want to close Application?”;
window.onbeforeunload = function () { return warnMessage };
$(document).ready(function () {
$(‘a[rel!=ext]’).click(function () { window.onbeforeunload = null; });
$(‘form’).submit(function () { window.onbeforeunload = null; });
});

Method 1 is the simple one, but this is has lack, every click a link or go to other page in application, confirmation always show up. If you have paging in your page, every click in next page, again confirmation always show up. It is very bother us, isn’t it?

Method 2, is improvement from method 1, confirmation will show up every any changes in a form or input form from user. If user forgets to save something in new or edit form, this will help to prevent lost input data. But, this method still has some lacks, still show up confirmation in every postback, especially in paging.

Method 3, this is the best one. This is according to my requirement that ignored confirmation in every postback happen especially in paging, also link in a page or to other page in application.

I collect this from some reference in Internet, one of it i.e stackoverflow.com and forget to save the link.