Monday, January 9, 2012

Browser Close Event - Javascript

Below is the sample html + java script source which helps to understand regarding how to fire the browser close event.
Beside below way of handling there is an another way. We can use use the body unload event and then in the unload event we will check the cursor position if it is near to window close button which mean user has tried to click on close button.
But this will not work if user says Alt+F4 or closes from task bar directly.

Scenario, like say if app should update database as logged out when user closes the browser.
This can be handled by calling a web page using XmlHttp request in the below "WindowClose" function.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">

function WindowClose(event) {
event = event || window.event;

var confirmClose = "This is to fire the close event of browser";

if (event) {
event.returnValue = confirmClose;
}
return confirmClose;
}
window.onbeforeunload = WindowClose;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

After running the above ones and while trying to close the browser, dialog appears as per below screen shot.

The same applies for Firefox and IE Browser

3 comments:

Anonymous said...

I and my buddies have already been digesting the great procedures from the website while suddenly got an awful suspicion I never expressed respect to the web blog owner for those strategies. The men appeared to be for this reason thrilled to study all of them and have without a doubt been enjoying these things. I appreciate you for indeed being simply considerate as well as for obtaining this kind of quality areas most people are really desperate to be informed on. Our sincere apologies for not saying thanks to you earlier.
10-32 X 3/4 Type 23 TCS / Unslotted / Ind Hex Washer Hd / 18-8 Stainless Steel / 3,000 Pc. Carton

Anonymous said...

Great write-up, I am regular visitor of one's web site, maintain up the excellent operate, and It is going to be a regular visitor for a long time.
Scarpa Women's Kailash GTX Lady Hiking Boot

Programming and Database Concepts said...

Thanks Folks,
really encouraging, looking forward for your in-reads, suggestions and comments.