我想在用户点击浏览器的关闭按钮时使用JavaScript发出提醒。我如何检测事件?
答案 0 :(得分:3)
您可以挂钩beforeunload
事件,以便在用户离开您的网页时执行某些操作。您无法直接检测关闭浏览器的用户。
以下是一个例子:
<!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>
答案 1 :(得分:1)
<body onunload="javascriptHere();">