JavaScript 如何检测浏览器或标签关闭
可以使用beforeunload事件来检测浏览器中的标签或窗口关闭。这可以用于在页面上有未保存的数据或用户错误关闭标签或浏览器时向用户发出警告。
使用addEventListener()方法可以在特定事件发生时设置一个函数。beforeunload事件在窗口及其资源要被卸载之前触发。当这个事件被触发时,网页是可见的,并且此时事件仍然可以取消。
事件处理程序应该调用preventDefault()来根据规范显示确认对话框。如果用户希望继续到新页面,则导航到新页面,否则取消导航。然而,老版本的浏览器可能不支持这种方法,需要使用一种传统的方法,其中事件处理程序必须返回一个字符串。这个返回的字符串可以是空的。
一些浏览器可能决定在用户与页面进行交互之前不显示任何确认框。这用于防止不需要或恶意的网站创建不必要的弹出窗口。用户可能需要与页面进行交互才能看到确认消息。这种方法适用于检测标签关闭或浏览器关闭。
语法:
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to detect browser or tab closing
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>Detect browser or tab closing</b>
<p>
The beforeunload function is triggered
just before the browser or tab is to be
closed or the page is to be reloaded.
Modern browsers require some interaction
with the page, otherwise the dialog box
is not shown.
</p>
<form>
<textarea placeholder = "Trigger an
interaction by writing something here">
</textarea>
</form>
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
</script>
</body>
</html>
输出: