This question already has an answer here:
I would like to replace an url without page refresh.
I need to change:
https://example.com/en/step1
to
https://example.com/en/step2
How to do that ?
This question already has an answer here:
I would like to replace an url without page refresh.
I need to change:
https://example.com/en/step1
to
https://example.com/en/step2
How to do that ?
Update
Based on Manipulating the browser history, passing the empty string as second parameter of
pushState
method (aka title) should be safe against future changes to the method, so it's better to usepushState
like this:You can read more about that in mentioned article
Original Answer
Use
history.pushState
like this:Update to answer Idan Dagan's comment
Q: Why not using
history.replaceState()
?A: From MDN
That means if you use
replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (becausereplaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.Update to add
window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using
pushState
, you can detect the back/forward button navigation by usingwindow.onpopstate
like this:As the first argument of
pushState
is an object, if you passed anobject
instead ofnull
, you can access that object inonpopstate
which is very handy, here is how:Update to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a
popstate
event using thehistory.state
property like this:When you use a function ...