How do I use JavaScript to modify the URL without reloading the page?

Using the History API

The HTML5 history API is the best choice for modern websites. It does the job well and also provides additional functionality. You can use either history.pushState() or history.replaceState()  to modify the URL in the browser, depending on your needs:

// Current URL: https://my-website.com/page_a
const nextURL = 'https://my-website.com/page_b';
const nextTitle = 'My new page title';
const nextState = { additionalInformation: 'Updated the URL with JS' };

// This will create a new entry in the browser's history, without reloading
window.history.pushState(nextState, nextTitle, nextURL);

// This will replace the current entry in the browser's history, without reloading
window.history.replaceState(nextState, nextTitle, nextURL);

Both methods accept the same arguments. This allows you to pass a customized serializable state object as the first parameter, a customized title (although most web browsers will ignore this parameter), or the  URL that you want to replace/add to the browser’s past history. You cannot navigate to a different website using the History API.

Using the Location API

The older Location API does not provide the best tools for the job as it reloads every page. You can still modify the URL using it, which is useful for older browsers. You can modify the URL, using either window.location.hreflocation.assign() or location.replace():

// Current URL: https://my-website.com/page_a
const nextURL = 'https://my-website.com/page_b';

// This will create a new entry in the browser's history, reloading afterwards
window.location.href = nextURL;

// This will replace the current entry in the browser's history, reloading afterwards
window.location.assign(nextURL);

// This will replace the current entry in the browser's history, reloading afterwards
window.location.replace(nextURL);

All three options will cause a page’s to reload. You can’t add any arguments to the URL setting API. You can set the URL using the Location API, but you won’t be restricted to the same-origin URLs. This could cause security issues if not taken care of.

 

Exit mobile version