<- all articles

Changing the browser URL without reloading the page

Sam Hendrickx

e.g. To keep the filters on a web page when the browser reloads is easy to accomplish with the browsers history API.

Assume we have a page like this (don’t mind the styling):

Example web page

You have some filters coffee, wine, etc and a list that’s going to be filtered with a result like below:

Filtering the webpage

To keep the list filtered after a reload you can use the history api, namely the history.pushState

It is as simple as:

history.pushState(null, ‘’, theUrlYouWantItToBe);

In our case:

const search = '?filter=["wine","milk"]';history.pushState(null, ‘’, location.origin + search);

You can find the full snippet below to play with:

To easily serve a local file you can use http-server

npm install http-server -g

Create an index.html file with the code from the snippet. In the folder serve the file with the following command

http-server

And boom! 💥

Written by

Sam Hendrickx

Want to know more?

Related articles