history.pushState 和 history.replaceState 可以在不刷新當前頁面的情況下更改URL,但是這樣就無法獲取通過AJAX得到的新頁面的內容了。
雖然各種HTML5文檔說 window.onpopstate 事件可以攔截 pushState 的消息,但在實際的測試中, onpopstate 根本沒有任何作用,無法攔截 pushState 的消息。
經過Google一番,才找到了正確獲取 pushState 事件的代碼
https://stackoverflow.com/a/25673911
// Add this:var _wr = function(type) { var orig = history[type]; return function() { var rv = orig.apply(this, arguments); var e = new Event(type); e.arguments = arguments; window.dispatchEvent(e); return rv; };};history.pushState = _wr('pushState');history.replaceState = _wr('replaceState');// Use it like this:window.addEventListener('pushState', function(e) { console.warn('THEY DID IT AGAIN!');});window.addEventListener('replaceState', function(e) { console.warn('THEY DID IT AGAIN!');});這段代碼改寫了 history 中原來的函數,然后自己激活一個事件
這樣就可以解決 pushState 無法激活事件的問題了
另外記得最好將這段代碼放在文檔加載前執行
以上這篇淺談通過JS攔截 pushState和replaceState事件就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答