判断浏览器关闭还是刷新

本文介绍了一种通过JavaScript实现的方法来判断用户是否刷新或关闭了浏览器窗口。利用window.onbeforeunload事件监听器和键盘事件keyCode来区分两种行为,并提供了一个简单的示例代码。
判断浏览器关闭还是刷新:

<html>
<head>
<script type="text/javascript">
var num=0;
window.onbeforeunload=function(){
if(num==0){
window.location.href="<%=basePath%>login.do";
}
num=0;
};
function cl(event) {
if(event.keyCode==116){
num++;
}
}
</script>
</head>
<body style="text-align: center;height: 100%;" onkeydown="cl(event)">
index
</body>
</html>


onclick方法也可以这样写:
window.document.onkeydown = disableRefresh;
function disableRefresh(evt){
alert(evt.keyCode);
};
在 Vue 应用中,判断浏览器刷新页面还是关闭页面是一个常见的需求,尤其是在需要处理清理逻辑或发送某些请求的场景下。可以通过 `beforeunload` 事件来实现这一功能。 ### 使用 `beforeunload` 事件 `beforeunload` 是浏览器提供的一个事件,当窗口、文档及其资源即将卸载时触发。可以结合 `pagehide` 或 `unload` 事件进行更精确的判断。 ```javascript window.addEventListener('beforeunload', (event) => { // 判断是否为页面刷新关闭 const isPageRefresh = performance.navigation.type !== PerformanceNavigation.TYPE_RELOAD; if (isPageRefresh) { console.log('页面正在关闭'); } else { console.log('页面正在刷新'); } // 阻止默认行为(可选) event.preventDefault(); event.returnValue = ''; // Chrome 需要设置 returnValue }); ``` #### 注意事项: - 在现代浏览器中,直接阻止页面关闭的行为受到限制,因此 `event.returnValue` 主要用于显示确认对话框。 - `performance.navigation.type` 提供了导航类型的信息,其中 `PerformanceNavigation.TYPE_RELOAD` 表示页面是通过刷新加载的 [^1]。 ### Vue 中的具体实现 在 Vue 应用中,可以在 `mounted` 生命周期钩子中添加监听器,并在 `beforeUnmount` 钩子中移除它以避免内存泄漏: ```vue <template> <div>App Component</div> </template> <script> export default { name: 'App', mounted() { window.addEventListener('beforeunload', this.handleBeforeUnload); }, beforeUnmount() { window.removeEventListener('beforeunload', this.handleBeforeUnload); }, methods: { handleBeforeUnload(event) { const isPageRefresh = performance.navigation.type !== PerformanceNavigation.TYPE_RELOAD; if (isPageRefresh) { console.log('页面正在关闭'); } else { console.log('页面正在刷新'); } // 阻止默认行为(可选) event.preventDefault(); event.returnValue = ''; // Chrome 需要设置 returnValue } } }; </script> ``` ### 其他方法 如果需要更复杂的逻辑,比如区分用户主动关闭页面浏览器崩溃等场景,可以考虑使用心跳检测机制与后端通信,但这通常适用于单页应用(SPA)中对会话状态管理的需求。 ### 总结 通过 `beforeunload` 事件结合 `performance.navigation.type` 可以有效判断浏览器刷新页面还是关闭页面。这种方法在 Vue 应用中易于集成,并且能够满足大多数实际需求。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值