Keep filters in the URL

Shareable links and a working Back button: write the state to the address, and read it back.

JavaScript · Keep filters in the URLAdvanced
function readState() {
  return Object.fromEntries(new URLSearchParams(location.search));
}

function writeState(patch, { replace = false } = {}) {
  const params = new URLSearchParams(location.search);
  for (const [k, v] of Object.entries(patch)) {
    v === '' || v == null ? params.delete(k) : params.set(k, v);
  }
  const url = location.pathname + (params.size ? '?' + params : '') + location.hash;
  history[replace ? 'replaceState' : 'pushState']({}, '', url);
}

window.addEventListener('popstate', () => console.log('state is now', readState()));
writeState({ q: 'php', page: 2 });
historypushStateurlstatefilters