Site icon Denis Bouquet

Change url parameters without refreshing the page with JavaScript

For tracking purpose, we sometimes want to update the page url parameters but not refresh that page (ie: single page application). For instance, if we have a progress tracking or to come back to a specific place later.

How to append parameters to an URL, but not do a page refresh/reload/redirect?

If you set a new window.location you will reload the page. If you want to avoid this, use JavaScript replaceState or pushState.

This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action. (developer.mozilla.org)

JavaScript: update parameters without reloading the page:

window.history.replaceState(null, null, '?step=1');
window.history.pushState('object or string', 'title', 'new url');

Example:

// currentStep is the variable name of the step 
window.history.replaceState(null, null, '?step='+currentStep );

How to get URL parameters in JavaScript:

const queryString = window.location.search;
if(queryString) {
  const urlParams = new URLSearchParams(queryString);
  const stepValue = urlParams.get('step');

  // do something with the value.
}

Hope that helps / can save you some time :)

Exit mobile version