How to “browser back” when using pushState?

丶灬走出姿态 提交于 2019-12-02 11:19:25

The normal behaviour for the back button is for the browser to go back to the previous document, but when you use pushState, there isn't a previous document.

The point of pushState is to keep the browser on the same document while updating the URL. This is accompanied by DOM changes applied with JavaScript.

It is a simulation of going to a new page.

To make the back button appear to work, you need to write a matching simulation of going to the previous page.

You can do this by listening for a popstate event.

Page <span id="p">1</span>

<button>Next</button>

<script>
document.querySelector("button").addEventListener("click", function () {
  document.getElementById('p').textContent++;
  history.pushState({}, "", "/" + document.getElementById('p').textContent);
});

addEventListener("popstate", function (e) {
  document.getElementById('p').textContent--;
  e.preventDefault();
});
</script>

push is for pushing... adding


you should go for history.back()

If you want to popState - emit popstate event on window or do history.replaceState()


If you want to cancell commented event: My answer will do the trick https://stackoverflow.com/a/44553087/5694206

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