Alert/Prevent Users From closing the browser

Here's a simple script that works on both IE and Mozilla and displays a confirmation box before closing the browser. You can use this script to detect if an activity is on and alert users about the same, before they close the browser.


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script type="text/javascript"> 

        window.onbeforeunload = function(e) {

            e = e || window.event;

            e.returnValue = "Your message here";

        };

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

 

    </div>

    </form>

</body>

</html>



You can use the same script on ASP.NET pages too




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Sandeep Aparajit said...

The pop-up is shown even if you navigate to other page of your own website. I wanted a solution wherein the user will be altered ONLY if he is closing the Browser window. Can you pls provide any pointers?

Sandeep
http://sandeep-aparajit.blogspot.com