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

人盡茶涼 提交于 2020-01-14 08:52:09

问题


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

<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.


回答1:


You get a popstate event only if you add one or more history entry/entries and later the user clicks the back button in the browser.

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.

You add a history entry with pushState method:

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

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

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


Exceptions:

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

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



来源:https://stackoverflow.com/questions/29500484/window-onpopstate-is-not-working-nothing-happens-when-i-navigate-back-to-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!