How To Update URL Parameters In Javascript Without Reloading?

Crazy Developer From India, who has more interest in programming than a main stream academic!
I have been a hardcore open-source developer building plugins for WordPress and WooCommerce since 2007. It has been an amazing 13-year journey, and I look forward to more!
I ❤️ Open Source!
In this post, we are going to learn how to change URL Parameters on a page using javascript but without reloading the website.
Backstory
When I saw websites updating their URL when loading content via Ajax. I was stunned & confused about how they are updating it.
When I tried using the below code it still reloaded the page.
location.href = 'https://example.com/?param1=value1';
So I decided to dig deep to find how it was done.
I know there are some javascript frameworks such as vueJS which support url routing but I wanted to get this done in VanillaJS so that I can use it in my applications.
How it's done?
This is a very simple thing to do in VanillaJS using built-in browsers' History.pushState(). All We need to do is just update the history with the new URL & Page title
function change_url_without_reload( title, url ) {
if( typeof ( history.pushState ) !== 'undefined' ) {
history.pushState( { page: title, url: url }, title, url );
}
}
MDN Docs
Browser Support Status
Live Demo
Source Code
https://github.com/varunsridharan/blog-demos/blob/main/how-to-update-url-parameters-in-javascript-without-reloading/index.html
Questions or feedback? Please comment below.
See all my projects at Github.
Follow me on Twitter for updates

