概述 window.onpopstate是popstate事件在window對象上的事件處理程序. 每當處於激活狀態的歷史記錄條目發生變化時,popstate事件就會在對應window對象上觸發. 若是當前處於激活狀態的歷史記錄條目是由history.pushState()方法建立,
或者由history.replaceState()方法修改過的, 則popstate事件對象的state屬性包含了這個歷史記錄條目的state對象的一個拷貝. 調用history.pushState()或者history.replaceState()不會觸發popstate事件. popstate事件只會在瀏覽器某些行爲下觸發,
好比點擊後退、前進按鈕(或者在JavaScript中調用history.back()、history.forward()、history.go()方法). 當網頁加載時,各瀏覽器對popstate事件是否觸發有不一樣的表現,Chrome 和 Safari會觸發popstate事件, 而Firefox不會. 語法 window.onpopstate = funcRef; funcRef 是個函數名. popstate事件 假如當前網頁地址爲http://example.com/example.html,則運行下述代碼後: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); };
//綁定事件處理函數. history.pushState({page: 1}, "title 1", "?page=1"); //添加並激活一個歷史記錄條目 http://example.com/example.html?page=1,條目索引爲1 history.pushState({page: 2}, "title 2", "?page=2"); //添加並激活一個歷史記錄條目 http://example.com/example.html?page=2,條目索引爲2 history.replaceState({page: 3}, "title 3", "?page=3"); //修改當前激活的歷史記錄條目 http://ex..?page=2 變爲 http://ex..?page=3,條目索引爲3 history.back(); // 彈出 "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // 彈出 "location: http://example.com/example.html, state: null history.go(2); // 彈出 "location: http://example.com/example.html?page=3, state: {"page":3}
即使進入了那些非pushState和replaceState方法做用過的(好比http://example.com/example.html)沒有state對象關聯的那些網頁, popstate事件也仍然會被觸發.
<body> Document <p>存入歷史</p> <script> // h5 history $(function () { $('p').click(function() {
// 瀏覽器顯示 http://192.168.1.223:8989/page1 history.pushState({'info': '測試'}, '標題', 'page1') }) }) </script> </body>
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/onpopstatehtml