In this article I will shoe you code to detect browser close
using jQuery in asp.net. In this when when you click on close button of browser
on that case it will give and JavaScript alert message that you are going to
close the browser.
Some of my previous articles are as follows: jQueryUI
Tooltip Using jQuery on Textbox MouseOver in Asp.Net, Show
and Hide Div on Button Click Using jQuery in Asp.Net | How to Use jQuery Toggle
Function on Click In Asp.net, Restrict
Number of Characters to be Entered in the TextArea Using jQuery in Asp.Net MVC,
Display
No of Characters Entered In TextArea Using jQuery, Free
Download eBook - Learning jQuery Deferreds | eBook To Learn jQuery Programming.
So for this article first we will create a new asp.net
application and add the jquery library reference in your application.
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
|
Now add the below jquery code in you page header.
<script language="javascript"
type="text/javascript">
$(document).ready(function () {
$(window).bind("beforeunload", function () {
return
confirm("You are about to close the
window");
});
});
</script>
|
In above code we are binding alert message that when user
will click on close button you will get the alert message. Here is the complete
code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DetectBrowserClose.WebForm1"
%>
<!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>Code to
Detect Browser Close Using jQuery In Asp.Net</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(window).bind("beforeunload",
function () {
return
confirm("You are about to close the window");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Please click on close window
</div>
</form>
</body>
</html>
|
Now view the page in browser.
This pop is coming not only when the browser is closed but also on the below activities..
ReplyDelete1. Refreshing the Page
2. Navigating between the pages.
3. On Click of any link on the page.
Can I get to fire this event only when the browser is closed? or any other events available to accomplish this?
I don't think so. but still i will check and get back to you, if problem is there in code with proper code.
DeleteHi This cod is developed for all the scenario which you have mention. In all three cases you are leaving the page.
Deleteif you are navigating on that case also you leaving the page as equal as closing. same for refresh and link click.
Thanks Pranav, I was specifically looking for an event that gets fired only when the browser is closed but not during the above scenarios.
Delete