15

我正在尝试添加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>

但是,当我导航回该页面时,我没有收到任何警报。

4

2 回答 2

29

popstate仅当您添加一个或多个历史记录条目并且稍后用户单击浏览器中的后退按钮时,您才会收到一个事件。

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

您使用以下方法添加历史记录条目pushState

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

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

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


例外:

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

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

于 2015-04-07T20:33:22.963 回答
0
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}"
于 2021-10-28T14:21:33.360 回答