views:

21

answers:

2

I want to give an alert using JavaScript when the user clicks the close button of the browser. How do I detect the event?

+1  A: 

You can hook the beforeunload event to do something when the user leaves your page. You can't directly detect the user closing the browser.

Here's an example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>
window.onbeforeunload = askWhetherToClose;
function askWhetherToClose(event) {
    var msg;

    msg = "You're leaving the page, do you really want to?";
    event = event || window.event;
    event.returnValue = msg;
    return msg;
}
</script>
</head>
<body>
<p>Close the browser window, or navigate to <a href="http://stackoverflow.com"&gt;StackOverflow&lt;/a&gt;&lt;/p&gt;
</body>
</html>

More on the MDC and MSDN pages. Use this knowledge only for good.

T.J. Crowder
Cross button is stand for BROWSER CLOSE BUTTON THE RED ICON X BUTTON.I want to open a new window when user will click on browser close button (the red icon).So i need to detect an event when user will click on Close button of browser.
Ajay_kumar
You want to open a new window when the user tries to close the window? Reminds me of dodgy sites that bombarded you with adverts back in the '90s. Happily, browsers protect users against this now, so it is impossible.
David Dorward
@Ajay: I've updated the answer with how you can implement things like StackOverflow's (and Gmail's, etc.) behavior double-checking whether the user really wants to leave the page with a half-composed message and such. You can't open a new window (reliably), nor would it be appropriate to do so.
T.J. Crowder
+1  A: 
<body onunload="javascriptHere();">
Bart van Heukelom
You should mention that it's general page leaving event, not just close button click event and that it's possible that this event will be blocked by browser in some cases. There is no safe way to detect that user is closing a window or is leaving your site.
calavera.info

related questions