通過JS攔截 pushState 和 replaceState 事件

來源:互聯網
上載者:User

標籤:ack   頁面   html   listener   函數   http   blog   div   line   

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 事件

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.