4

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)

quarks
  • 33,478
  • 73
  • 290
  • 513
  • 1
    What do you mean? why wouldn't it function as normal? or do you mean you want to use [replaceState()](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_replaceState()_method) ? – Faris Jun 14 '17 at 19:22
  • No I mean when user press the back button it does not go back to the previous page – quarks Jun 15 '17 at 02:27
  • @xybrek why does it not go back if user presses the browser back button? Is your browser defect? – Black Jun 15 '17 at 08:54
  • 1
    @Black — Because they are using pushState! – Quentin Jun 15 '17 at 08:59

2 Answers2

8

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>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

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

Daniel Mizerski
  • 1,123
  • 1
  • 8
  • 24