要判断网页是被关闭还是被刷新,需要使用onbeforeunload事件和event.currentTarget.performance.navigation.type属性。
要判断网页是被关闭还是被刷新,需要使用onbeforeunload事件和event.currentTarget.performance.navigation.type属性。
onbeforeunload事件会在页面关闭或者刷新时被触发,可以作为判断依据。而event.currentTarget.performance.navigation.type属性在页面刷新时值为1,在页面关闭时值为2。
下面是具体的实现步骤:
- 在页面中添加
onbeforeunload事件。
<script>
window.addEventListener('beforeunload',function(event){
if(event.currentTarget.performance.navigation.type == 1) {
// 页面是通过刷新退出的
} else if(event.currentTarget.performance.navigation.type == 2) {
// 页面是通过关闭退出的
}
});
</script>
- 在事件中判断
event.currentTarget.performance.navigation.type的值,从而得知页面是通过刷新退出还是通过关闭退出。
这里提供两个简单的示例:
示例一
<!DOCTYPE html>
<html>
<head>
<title>Javascript判断网页是关闭还是刷新</title>
</head>
<body>
<p>测试网页是否关闭或者刷新。</p>
<button>刷新页面</button>
<script>
window.addEventListener('beforeunload',function(event){
if(event.currentTarget.performance.navigation.type == 1) {
alert('页面是通过刷新退出的');
} else if(event.currentTarget.performance.navigation.type == 2) {
alert('页面是通过关闭退出的');
}
});
document.querySelector('button').addEventListener('click', function(event){
location.reload();
});
</script>
</body>
</html>
示例二
<!DOCTYPE html>
<html>
<head>
<title>Javascript判断网页是关闭还是刷新</title>
</head>
<body>
<p>测试网页是否关闭或者刷新。</p>
<form method="post">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<br>
<button type="submit">登录</button>
</form>
<script>
window.addEventListener('beforeunload',function(event){
if(event.currentTarget.performance.navigation.type == 1) {
alert('页面是通过刷新退出的');
} else if(event.currentTarget.performance.navigation.type == 2) {
alert('页面是通过关闭退出的');
}
});
</script>
</body>
</html>
这两个示例分别展示了在按钮点击和表单提交时,如何判断网页是被关闭还是被刷新。需要注意的是,在表单提交时,如果需要在提交前确认是否退出,可以使用window.confirm方法来实现。
编程基础网
本文标题为:javascript判断网页是关闭还是刷新
基础教程推荐
猜你喜欢
- 爬取今日头条Ajax请求 2023-02-22
- 前端性能优化及技巧 2024-01-08
- 获取当前网页document.url location.href区别总结 2023-12-28
- 从零开始用electron手撸一个截屏工具的示例代码 2023-12-15
- 关于 vuejs2:\\”TypeError: Cannot read property \\ 2022-09-15
- 利用 FormData 对象和 Spring MVC 配合实现Ajax文件下载功能 2023-02-14
- CSS重要属性之float学习心得(分享) 2024-01-09
- 移动端开发1px线的理解与解决办法 2024-01-17
- 14款经典网页图片和文字特效的jQuery插件-前端开发必备 2024-01-16
- 基于js中的存储键值对以及注意事项介绍 2023-12-27
