How can you set URL parameters using History.pushState()
to avoid browser refreshes? If there is a not a simple JS solution, is there already a popular library or built in function for jQuery?
Here is a relevant SO question, where the accepted answer does not actually work according to comments & my test (it removes the query string instead of updating a value): history.pushState() change query values
Just to be clear, I am referring to the URL parameters in a query string:
http://google.com/page?name=don
so we could change don
to tim
without causing a reload.
Here is one possible solution I found. However I'm nervous about using a JS library that only has 2 followers :P
Answering to the question in your comment, you'd be able to read those properties from
history.state
, a property that holds the value of the stat for the current URL. Whenever you go back and forward you'll receive apopstate
event and you will be able tor read the state you pushed, which is far easier than dealing with urls.Of course, when you go back or forward to a new entry in the history list pushed with
pushState()
orreplaceState()
the page does not reload.You can read more about the History object in the MDN.
Here is a simple function I wrote it isn't as neat as the above answer but it does the trick...
You can just use
queryString.push('my_param_key', 'some_new_value')
from the small library below.It will update your URL param using history.push, so the browser will not refresh.
It will only affect the param you wish to change, it will leave the path and other params unaffected.