Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active June 30, 2021 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiaslopezd/c8481e1e94d96f95949a6f6e15abc2ed to your computer and use it in GitHub Desktop.
Save matiaslopezd/c8481e1e94d96f95949a6f6e15abc2ed to your computer and use it in GitHub Desktop.
Set and get search params without reload
function getSearchParams() {
const { search } = window.location;
const params = new URLSearchParams(search);
const query = {};
params.forEach((value, key) => {
query[key] = value;
});
return query;
}
function setSearchParams(newParams = {}, override = false) {
const { search, protocol, host, pathname } = window.location;
const current = override ? {} : search;
const params = new URLSearchParams(current);
const keys = Object.keys(newParams);
keys.forEach(param => params.set(param, newParams[param]));
const title = window.title;
const url = `${protocol}//${host}${pathname}?${params.toString()}`;
window.history.pushState({ path: url }, title, url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment