brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: history.replaceState keeps web page filters in the address bar

Web
~/tips/tip-web-replacestate-filters

function setFilter(name, value) {

Make a filtered view shareable without adding a history entry per click.

If I filter a product list and send you the link, you should see the same list. Writing the choice into the address makes that work.

function setFilter(name, value) {
  const url = new URL(location.href);
  url.searchParams.set(name, value);
  history.replaceState(null, '', url);
}

setFilter('sort', 'price');

The address now ends in ?sort=price and the page did not reload. On load, read it back so the view matches:

const sort = new URL(location.href).searchParams.get('sort');

I pick replaceState over pushState for filters. With pushState every tick of a checkbox adds a step to the history, and the Back button then crawls through each one before it leaves the page. For real navigation, such as opening a detail view, pushState is the better choice, together with a popstate listener.

Changing the address does not change what the page shows, that is still your code’s job. The new URL must be on the same origin. And keep secrets out of it, since addresses end up in history and server logs.

Further reading: MDN: History replaceState()

More Web tips async function sha256(text) { url = URL.createObjectURL(file); and open <span translate="no">Home Assistant</span> in your browser. …the page behind the drawer… inputmode="numeric" autocomplete="one-time-code"> All Web tips (6) All topics

Link