Javascript window.onpopstate 不工作;当我导航回页面时没有任何反应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29500484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:28:19  来源:igfitidea点击:

window.onpopstate is not working; nothing happens when I navigate back to page

javascripthistorypopstate

提问by Erica Stockwell-Alpert

I'm trying to add window.onpopstateon one of the pages on my site, but nothing is happening. I put this script on the page:

我正在尝试添加window.onpopstate我网站上的其中一个页面,但没有任何反应。我把这个脚本放在页面上:

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

I have also tried:

我也试过:

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

However, I don't get any alerts when I navigate back to the page.

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

回答by Paolo

You get a popstateevent only if you add one or more history entry/entries and later the user clicks the backbutton in the browser.

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

Adding entries to the browser history lets you change the URL (just as the user navigates to another page) but without actually loading a new page.

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

You add a history entry with pushStatemethod:

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

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

As you add one entry and the user clicks backthe URL switches back to the previous one but the page at that address is not loaded. A popstateevent is triggered instead.

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

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

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



Exceptions:

例外:

Older browsers don't support popstateevents and manipulation of the browser's history.

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

Some browsers (ex. Safari) trigger a popstateevent also when the page is actually loaded.

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