Modifying a query string without reloading the page Modifying a query string without reloading the page javascript javascript

Modifying a query string without reloading the page


If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:

if (history.pushState) {    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';    window.history.pushState({path:newurl},'',newurl);}

It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values. And of course that it requires modern browsers that can process HTML5 History API.

For more information:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history


I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.

function insertUrlParam(key, value) {    if (history.pushState) {        let searchParams = new URLSearchParams(window.location.search);        searchParams.set(key, value);        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();        window.history.pushState({path: newurl}, '', newurl);    }}


I've used the following JavaScript library with great success:

https://github.com/balupton/jquery-history

It supports the HTML5 history API as well as a fallback method (using #) for older browsers.

This library is essentially a polyfill around `history.pushState'.