[英]Detect if the user arrived to the current page via the browser back button
我有一個網站,如果用戶導航到某個頁面,那么他會根據頁面上的某些條件收到對話框通知。 用戶可以從該頁面導航到其他頁面,當然也可以按這些頁面上的后退按鈕導航回該頁面。
我想檢測用戶是否通過后退按鈕到達此頁面,因此不會再次顯示對話框通知(因為用戶已經看到了)。
有沒有辦法可靠地檢測到這一點?
你最好的可能是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.