我有一个网站,如果用户导航到某个页面,那么他会根据页面上的某些条件收到对话框通知。用户可以从此页面导航到其他页面,当然也可以按这些页面上的后退按钮导航回此页面。
我想检测用户是否通过后退按钮到达此页面,因此对话框通知不会再次显示(因为用户已经看到它)。
有没有办法可靠地检测到这一点?
你最好的可能性可能是
window.onpageshow = function(){};
窗口上 pageshow 事件的事件处理程序属性。
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
输入技巧不再起作用。这是我使用的解决方案:
if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
alert('Got here using the browser "Back" or "Forward" button.');
}
最好的(虽然不是非常可靠)的方法是使用 Javascript 历史对象。您可以查看history.previous 页面以查看它是否是该系列中的下一个页面。这不是一个很好的解决方案,但也许是解决这个问题的唯一方法。
我喜欢在输入字段中使用值:-
<input type="hidden" id="fromHistory" value="" />
<script type="text/javascript">
if (document.getElementById('fromHistory').value == '') {
document.getElementById('fromHistory').value = 'fromHistory');
alert('Arrived here normally');
} else {
console.log('Arrived here from history, e.g. back or forward button');
}
</script>
这是可行的,因为如果浏览器从历史记录导航回该字段,浏览器会使用 javascript 放入的值重新填充该字段的值:-)
有 window.performance navigationTiming API 可以通过按后退按钮来检测页面是否加载。
if (window.performance) {
var navEntries = window.performance.getEntriesByType('navigation');
if (navEntries.length > 0 && navEntries[0].type === 'back_forward') {
console.log('this page is load from back/forward');
} else {
console.log('This is normal page load');
}
} else {
console.log("browser doesn't support this API");
}
还有一个已弃用的 api 以及检测后退按钮:
if (window.performance) {
if (window.performance.navigation
&& window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
console.log('this page is load from back/forward');
} else {
console.log('This is normal page load');
}
} else {
console.log("browser doesn't support this API");
}
您可以将两者结合起来以支持最旧的浏览器。