[英]How to detect the back button
我已經設置了一個頁面,我在其中使用以下代碼,因此當您單擊鏈接時,內容和 URL 會更改而不刷新:
window.history.pushState("object or string", "title", "/photo.php");
但是當用戶點擊后退按鈕時,內容不會變回去。 如何檢測后退按鈕?
您可以像這樣使用onpopstate
。 當使用導航按鈕時,它也會被觸發。
window.onpopstate = function(e) { // executed when using the back button for example
alert("Current location: " + location.href); // location.href is current location
var data = e.state;
if(data) {
alert(JSON.stringify(e.state)); // additional data like your "object or string"
}
};
這個答案已經給出,但我會嘗試解釋我使用 pushState 的理解考慮你的 url 是“google.com/gmail”
1.將 currentURL 設為臨時 URL,這樣你的瀏覽器就會顯示這個 URL。 在這一步,堆棧中將有一個 URL,即google.com/gmail#!/tempURL
。
history.replaceState(null, document.title, location.pathname+"#!/tempURL");
2.Push the previousURL 作為新狀態,所以現在你的瀏覽器將顯示 previousURL 即google.com/gmail
。
history.pushState(null, document.title, location.pathname);
堆棧的當前狀態
第一個元素: google.com/gmail
最后一個元素: google.com/gmail#!/tempURL
3.現在添加監聽器監聽事件
window.addEventListener("popstate", function() {
if(location.hash === "#!/tempURL") {
history.replaceState(null, document.title, location.pathname);
//replaces first element of last element of stack with google.com/gmail so can be used further
setTimeout(function(){
location.replace("http://www.yahoo.com/");
},0);
}
}, false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.