pushState不会触发popstate事件

回到文章>>

COPYHTML

<div class="container"> <nav> <p><button class="back">back</button></p> <p><button class="go">go</button></p> <p>注意url的变化:<button class="pushstate">pushState</button></p> <p>注意url的变化:<button class="replacestate">replaceState</button></p> </nav> <div id="app">当前URL:<span></span></div> </div>

COPYJAVASCRIPT

class HistoryRouter { constructor() { this.refresh = this.refresh.bind(this); window.addEventListener("load", this.refresh, false); window.addEventListener("popstate", this.refresh, false); } refresh(event) { document.querySelector("#app span").innerHTML = location.pathname; } } new HistoryRouter(); document.querySelector(".back").addEventListener("click", function () { window.history.back(); }); document.querySelector(".go").addEventListener("click", function () { window.history.go(1); }); document.querySelector(".pushstate").addEventListener("click", function () { const url = Math.random().toString(36).slice(-6) + ".html"; window.history.pushState({}, "", url); }); document.querySelector(".replacestate").addEventListener("click", function () { const url = Math.random().toString(36).slice(-6) + ".html"; window.history.replaceState({}, "", url); });
新窗口打开