I have a button in body that once clicked, it should add an extra query parameter in the URL.
let addParam;
const button = document.createElement("BUTTON");
button.textContent = "Add";
document.body.prepend(button);
button.addEventListener("click", () => {
const url = new URL(window.location.href);
url.searchParams.set("param", "value");
window.history.pushState({ path: url.href }, "", url.href);
addParam = addParam ? false : true;
});
It works fine, the problem is that the current URL contains already a query parameter in the form of ?path=path/to/file
, so when we set another parameter with set(key, value)
, it changes the ?path=path/to/file
to ?path=path/to/file
. Is there a way I can prevent that from happening and keeping the original URL?
CodePudding user response:
Note that both URLs mean the same thing. I'm guessing you prefer the one with /
instead of the encoded form of it because it's more obvious to people reading the URL.
This may vary by browser, but on Chromium-based browsers it seems that it keeps the /
if it's in the URL you pass to pushState
. It's the URLSearchParams
that's encoding the /
.
I originally posted a solution doing string concatenation with encodeURIComponent
instead, but my solution was doing an append
, not a set
. Your code is using set
. Fortunately I'd also included a second solution: You can convert /
to /
after adding to the search params and converting them to a string:
const { origin, pathname, search } = window.location;
const searchParams = new URLSearchParams(search);
searchParams.set("param", "value");
const paramsString = searchParams.toString().replace(///gi, "/");
const url = `${origin}${pathname}?${paramsString}`;
window.history.pushState({ path: url }, "", url);
addParam = addParam ? false : true;
Note that I don't advocate this. I'd stick with the code you have. But it's your project, so you get to decide. :-)