JavaScript, the language of the web, has built-in features to access and modify the URL of the current browser page. For almost all URL accessing and modification needs, the window.location
object would usually suffice.
Recently, I encountered a problem with an application I was building: what happens when you need to modify the URL based on a user action (eg, change URL on input change to enable bookmarking of the resulting data)?
window.location URL modification forces a reload
Setting window.location.href
can modify the URL of a page, but it causes the page to reload and in this case, that is undesirable
This reloading occurs because setting the window.location.href
value navigates to the newly specified URL not just changing its value.
The solution : window.history ๐
The window.history
object stores the state of the browser session history which can be accessed and modified using its built-in methods.
Two of those methods which enable us to modify the URL in response to a user action (eg. input change) are replaceState
and pushState
.
Both methods receive the parameters;
- state (an object that will correspond to the new history entry but can be set to null ),
- unused ( an empty string passed for historical purposes ) and an optional
- url ( which in our case is not optional ๐).
history.replaceState()
This method replaces the current state of the browser history without reloading. One caveat of this is that clicking the back button will not navigate to the previous state as that will be completely removed.
Example
//previous state URL = https://previous.html
const stateObject = {title : "New title"};
history.replaceState(stateObject, '', 'new.html');
//the new URL = https://new.html
Now the URL is changed and the page does not reload!
history.pushState()
This method creates a new history entry for the current document.
Example
//previous state URL = https://previous.html
const stateObject = {title : "New title"};
history.pushState(stateObject, '', 'new.html');
//the new URL = https://new.html
Conclusion
There you have it, That's how to modify the page URL without reloading.
If you have any ideas or you spotted a bug please leave a comment.
I hope this post helps you learn as I learn too.