如何检查用户是否正在刷新页面或导航到其他页面 [英] How to check if user is refreshing the page or navigating to other page

查看:134
本文介绍了如何检查用户是否正在刷新页面或导航到其他页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方案:每当用户离开页面时,我都想在本地存储中设置一些变量.

Scenario: I want to set some variable in my localstorage whenever user leaves the page.

使用window.onbeforeunload我得到用户即将离开页面的事件.但是我想在用户刷新时设置不同的变量值,并在页面导航上设置不同的

Using window.onbeforeunload I get the event that user is about to leave the page. But I want to set different variable value when user refreshes and different on page navigation

var someVar;
//when refresh someVar = 1;
//When user clicks on any link which is not the same page, someVar =2

是否可以检测用户是否正在刷新或即将离开页面?

Is this possible to detect if user is refreshing or about to leave page?

推荐答案

根据您的评论,我正在更新我的答案.您无法在beforeunload事件或任何其他方法上检测导航类型,因为它取决于浏览器.但是,我可以为您提供一种在页面加载后进行回退或刷新的方法.我希望它会有用.

Based on your comment I am updating my answer. You can't detect navigation type on beforeunload event or with any other method because it is browser dependent. But I can provide you a way to detect back or refresh after the page loaded. I hope it will be useful.

请检查性能导航

if (performance.navigation.type == PerformanceNavigation.TYPE_RELOAD){
 //Reload
}

if (performance.navigation.type == PerformanceNavigation.TYPE_BACK_FORWARD){
 //Back Button
}

这篇关于如何检查用户是否正在刷新页面或导航到其他页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆