There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it ( document. location ) then it will reload the page.
In fact, JavaScript provides the location object, a part of the window object, which allows you to perform different URL-related operations.
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 use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
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 (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 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 using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 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 the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
When you use a function ...
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With