首先我想提一句MDN上的错误:“The persisted
read-only property indicates if a webpage is loading from a cache.”,这是MDN上的原话。意思是说可以通过 persisted属性来判断当前页面是否从浏览器缓冲区加载的。而且还给出了一张浏览器的兼容统计:
于是我按照此思路写了两个html页面来模拟点击链接跳转,然后点击浏览器返回按钮,在控制台上打印出persisted
属性值的变化。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>如何判断页面是通过链接打开还是通过后退按钮返回打开的?</title>
</head>
<body>
<a href="./test.html">测试页面</a>
<script>
window.addEventListener('pageshow', function (event) {
console.log('event.persisted: '+ event.persisted)
},false);
</script>
</body>
</html>
下面是我分别在Chrome和Firefox上的测试结果:
这个测试结果说明persisted属性并不能够用来判断页面是通过链接打开还是通过后退按钮返回打开的!!!
于是想到还有一个window.performance.navigation.type属性可以帮我解决这个问题。
window.performance
是W3C性能小组引入的新的API,目前IE9以上的浏览器都支持。
window.performance.navigation.type包含三个值:
0 : TYPE_NAVIGATE (用户通过常规导航方式访问页面,比如点一个链接,或者一般的get方式)
1 : TYPE_RELOAD (用户通过刷新,包括JS调用刷新接口等方式访问页面)
2 : TYPE_BACK_FORWARD (用户通过后退按钮访问本页面)
最后我将代码改写成如下形式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>如何判断页面是通过链接打开还是通过后退按钮返回打开的?</title>
</head>
<body>
<a href="./test.html">测试页面</a>
<script>
window.addEventListener('pageshow', function (event) {
if(event.persisted || window.performance && window.performance.navigation.type == 2){
console.log('window.performance.navigation.type: '+ window.performance.navigation.type)
// location.refresh(); //此处可以写你的实际应用的代码
}
},false);
</script>
</body>
</html>
经过测试在Chrome和Firefox上都可以。