0

I have code.

window.addEventListener('popstate', function (e) {
  // The URL changed...
  console.log(e);
});
setInterval(() => {
  history.pushState(null, "Other page", \`/${Math.ceil(Math.random() * 200)}\`)
}, 1000);

So, it changes the url of page every second to not same. But I do not get the event object in console. Why?

1 Answer 1

1

See mdn:

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript).

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but how to handle change of url by history.pushState or history.replaceState?
You're calling those functions explicitly so you know when you are changing the history. Just make whatever DOM changes you like at the same time you manipulate the history. The popstate event is there so you can change things back when the user hits the back button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.