繁体   English   中英

检测用户是否通过浏览器后退按钮到达当前页面

[英]Detect if the user arrived to the current page via the browser back button

我有一个网站,如果用户导航到某个页面,那么他会根据页面上的某些条件收到对话框通知。 用户可以从该页面导航到其他页面,当然也可以按这些页面上的后退按钮导航回该页面。

我想检测用户是否通过后退按钮到达此页面,因此不会再次显示对话框通知(因为用户已经看到了)。

有没有办法可靠地检测到这一点?

MDN 窗口事件列表

你最好的可能是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 放入的值重新填充该字段的值:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM