在JavaScript中,判断浏览器是否刷新可以通过多种方法实现,以下是一种常见的方法:
sessionStorage
:在页面加载时设置一个标志,如果这个标志已经存在,则说明页面是刷新的。performance.navigation
:这个API可以提供页面导航的信息,包括是否是通过刷新加载的。sessionStorage
// 在页面加载时执行
window.addEventListener('load', function() {
if (sessionStorage.getItem('isPageRefreshed') === 'true') {
console.log('页面是通过刷新加载的');
} else {
console.log('页面是首次加载的');
sessionStorage.setItem('isPageRefreshed', 'true');
}
});
解释:
sessionStorage
中没有isPageRefreshed
项,因此会设置该项为true
。sessionStorage
中已经有isPageRefreshed
项,且值为true
,因此可以判断页面是通过刷新加载的。performance.navigation
if (performance.navigation.type === performance.navigation.TYPE_RELOAD) {
console.log('页面是通过刷新加载的');
} else {
console.log('页面是首次加载的或通过其他方式导航来的');
}
解释:
performance.navigation.TYPE_RELOAD
的值为1,表示页面是通过刷新加载的。performance.navigation
API在一些现代浏览器中可能已经被弃用,建议使用performance.getEntriesByType('navigation')
来替代。performance.getEntriesByType
window.addEventListener('load', function() {
const navigationEntries = performance.getEntriesByType('navigation');
if (navigationEntries.length > 0 && navigationEntries[0].type === 'reload') {
console.log('页面是通过刷新加载的');
} else {
console.log('页面是首次加载的或通过其他方式导航来的');
}
});
解释:
performance.getEntriesByType('navigation')
返回一个包含导航信息的数组。type
属性为reload
,则表示页面是通过刷新加载的。通过以上方法,你可以有效地判断浏览器是否刷新,并根据需要执行相应的逻辑。
领取专属 10元无门槛券
手把手带您无忧上云