Dec 4, 2011

Catch Browser Close Event Javascript

In this post, I am sharing the code to catch the browser close event and write code to perform some action when the browser is closed.

Ajax is used to request the webpage when the browser is closed.

Default1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default1" %>
<!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" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script language="javascript" type="text/javascript">
        function window.onbeforeunload() {
            $.ajax({
                type: "POST",
                url: "exit.aspx/OnClose",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // Do something interesting here.
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>
Exit.aspx.cs
using System;
using System.Web.Services;
public partial class exit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    } 

    [WebMethod]
    public static void OnClose()
    {
        //write code here
    }
}