最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to "browser back" when using pushState? - Stack Overflow

programmeradmin3浏览0评论

I have this code:

window.history.pushState(newUrl, "", newUrl);

My question is, how to make sure that when doing pushState the browser back button will function as normal or in other words should go "back"?

(without using jQUery)

I have this code:

window.history.pushState(newUrl, "", newUrl);

My question is, how to make sure that when doing pushState the browser back button will function as normal or in other words should go "back"?

(without using jQUery)

Share Improve this question asked Jun 14, 2017 at 19:18 quarksquarks 35.3k82 gold badges308 silver badges546 bronze badges 4
  • 1 What do you mean? why wouldn't it function as normal? or do you mean you want to use replaceState() ? – Faris Commented Jun 14, 2017 at 19:22
  • No I mean when user press the back button it does not go back to the previous page – quarks Commented Jun 15, 2017 at 2:27
  • @xybrek why does it not go back if user presses the browser back button? Is your browser defect? – Black Commented Jun 15, 2017 at 8:54
  • 1 @Black — Because they are using pushState! – Quentin Commented Jun 15, 2017 at 8:59
Add a ment  | 

2 Answers 2

Reset to default 13

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 acpanied 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 mented event: My answer will do the trick https://stackoverflow./a/44553087/5694206

发布评论

评论列表(0)

  1. 暂无评论