window.onpopstate不工作;当我导航回页面时,不会发生任何事情



我正试图在我的网站上的一个页面上添加window.onpopstate,但什么也没发生。我把这个脚本放在页面上:

<script type="text/javascript">
  window.addEventListener('popstate', function(event) {
    if (event.state) {
      alert(event.state);
    }
  }, false);
</script>

我也试过:

<script type="text/javascript">
  window.onpopstate = function() {
    alert("popped!");
  }
</script>

但是,当我导航回页面时,不会收到任何警报。

只有添加一个或多个历史条目,然后用户单击浏览器中的back按钮,才能获得popstate事件。

在浏览器历史记录中添加条目可以更改URL(就像用户导航到另一个页面一样),但无需实际加载新页面。

使用pushState方法添加历史记录条目:

history.pushState({}, '', '/newpage');

当您添加一个条目,并且用户单击返回时,URL会切换回上一个,但该地址的页面不会加载。而是触发popstate事件。

请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history


异常:

较旧的浏览器不支持popstate事件和对浏览器历史记录的操作。

某些浏览器(例如Safari)在实际加载页面时也会触发popstate事件。

window.onpopstate = function(event) {
  alert(`location: ${document.location}, state: ${JSON.stringify(event.state)}`)
}
history.pushState({page: 1}, "title 1", "?page=1")
history.pushState({page: 2}, "title 2", "?page=2")
history.replaceState({page: 3}, "title 3", "?page=3")
history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back() // alerts "location: http://example.com/example.html, state: null"
history.go(2)  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"

最新更新