Is there a way to set the values of a querystring using javascript?
My page has a filter list that when clicked, it will alter the in-page results pane on the right hand side.
I'm trying to update to the querystring values of the url, so if the user leaves the page, then clicks the "back" buttons they'll be return to the last filter selection set.
For example:
Landing: foo.html
Click 1: foo.html?facets=bar
Click 2: foo.html?facets=bar|baz
Click 3: foo.html?facets=bar|baz|zap
Is this possible?
-
1Might be better achieved using a filter values cookie?Dan– Dan2011年04月05日 01:37:13 +00:00Commented Apr 5, 2011 at 1:37
-
You might take a look at Backbone, especially it's Backbone.Router class.acme– acme2012年04月12日 07:46:14 +00:00Commented Apr 12, 2012 at 7:46
3 Answers 3
You can use URLSearchParams. Just note that it isn't available for Internet Explorer 11.
// Get current URL parts
const path = window.location.pathname;
const params = new URLSearchParams(window.location.search);
const hash = window.location.hash;
// Update query string values
params.set('numerical', 123);
params.set('string', 'yummy');
params.set('multiple', ['a', 'b', 'c']);
params.set('foreignChar', 'é');
// Encode URL
// numerical=123&string=yummy&multiple=a%2Cb%2Cc&foreignChar=%C3%A9
console.log(params.toString());
// Update URL
window.history.replaceState({}, '', `${path}?${params.toString()}${hash}`);
1 Comment
location.hash
after params.toString
It is possible, but it will refresh the page.
document.location = "?facets=bar";
If you don't care about browser support, you can use the HTML5 history.pushState.
2 Comments
history.pushState
.You can use Javascript to change the hash (the #hash-part of the URL), but changing the query string means you have to reload the page. So, no, what you want to do is not possible in that way.
An alternative is to use Javascript to change the hash, then check the hash on page load to change your results dynamically. You're looking for something like jQuery Address.