{"id":1923,"date":"2020-09-21T06:24:27","date_gmt":"2020-09-20T22:24:27","guid":{"rendered":"https:\/\/www.intelliwolf.com\/?p=1923"},"modified":"2020-09-21T06:24:29","modified_gmt":"2020-09-20T22:24:29","slug":"update-url-parameters-without-refreshing-browser","status":"publish","type":"post","link":"https:\/\/wordpress-757293-2559390.cloudwaysapps.com\/update-url-parameters-without-refreshing-browser\/","title":{"rendered":"How To Update URL Parameters Without Refreshing The Browser"},"content":{"rendered":"\n
I'm building a project where the user will change the state of the website and we want that to be reflected in the URL, so they can share it with others and everyone can easily see which combination of elements they chose.<\/p>\n\n\n\n
How to update URL parameters using JavaScript without refreshing the browser<\/strong>: Use window.history.replaceState()<\/em> along with the current URL and whatever parameters you want to add.<\/p>\n\n\n\n Here's the basic code to make it work:<\/p>\n\n\n\n I've put currentURL<\/em> into a const<\/em> so that it won't change, allowing me to update the parameters. If you put it as a var<\/em> inside the click function, you'll end up adding ?v=1<\/em> to the end of what you have there. If the user clicks twice, the url would be https:\/\/example.com\/test\/?v=1?v=1<\/em>, but we want to change the value of v<\/em>.<\/p>\n\n\n\n This is the simplest implementation of the code. When the user clicks on the link with the id \"changer\"<\/em>, it prevents the link registering, then updates the URL.<\/p>\n\n\n\nconst currentURL = window.location.href;\n$(\"#changer\").click(function (e) {\n e.preventDefault();\n window.history.replaceState(\"\", \"\", currentURL + \"?v=1\");\n}<\/code><\/pre>\n\n\n\n