Close button detection using JavaScript
I want to give an alert using JavaScript when the user clicks the close button of the browser. How do I det开发者_如何学Cect the event?
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">StackOverflow</a></p>
</body>
</html>
More on the MDC and MSDN pages. Use this knowledge only for good.
<body onunload="javascriptHere();">
精彩评论