迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中检测浏览器或标签页关闭事件

作者:迹忆客 最近更新:2023/03/10 浏览次数:

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() 用于显示弹出窗口以供进一步确认。用户在这里有两个选择,他们可以导航到另一个页面或取消事件并保留在当前页面上。

输出:

在 javascript 中检测浏览器或标签关闭事件 - 输出

你可能对为什么我们必须填写 <textarea> 以获得所需结果有疑问。

在用户与网页交互之前,一些网络浏览器可能不会决定是否应该显示确认对话。

通过这种方式,我们可以检测到两个事件,标签页关闭和关闭浏览器窗口。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便