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" "">

<html xmlns="">
<head runat="server">
<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;
<form id="form1" runat="server">


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

No comments:

Post a Comment