在 JavaScript 中检测浏览器或标签页关闭事件
beforeunload
事件用于检测浏览器或标签页是否正在关闭或网页是否正在重新加载。
beforeunload
事件提醒用户。addEventListener()
函数在事件发生时监听事件。
在卸载窗口及其资源之前,会触发 beforeunload
事件。
HTML 代码 (index.html
):
<!DOCTYPE html>
<html>
<head>
<title>
Detect Browser or Tab Closing Event in JavaScript
</title>
<script src = "./script.js"></script>
</head>
<body>
<h1>
Detect Browser or Tab Closing Event in JavaScript
</h1>
<p>
The beforeunload event is fired just
before the closing the tab or browser
window or reloading the page.
In modern web browsers, you may have
to interate with the web
page to get the confirmation dialog.
</p>
<form>
<textarea placeholder = "Write few words here to trigger an
interaction">
</textarea>
</form>
</body>
</html>
JavaScript 代码(script.js
):
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
在这里,preventDefault()
用于显示弹出窗口以供进一步确认。用户在这里有两个选择,他们可以导航到另一个页面或取消事件并保留在当前页面上。
输出:
你可能对为什么我们必须填写 <textarea>
以获得所需结果有疑问。
在用户与网页交互之前,一些网络浏览器可能不会决定是否应该显示确认对话。
通过这种方式,我们可以检测到两个事件,标签页关闭和关闭浏览器窗口。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。