Vanilla JavaScript Update URL without Refresh


Changing a URL with JavaScript without refreshing

28 Jun, 2020 · 2 min read

Today we are looking into updating the URL without a refresh. We can access and modify the URL states using the History API.

The cool part is it has superb browser support!

JavaScript History API

The history API is a set of methods used to manipulate history. For instance, we can go forward and backward, just like clicking the buttons in your browser.

Also, check out this article about other History API methods

JavaScript history.pushState

Today’s focus is on the method called pushState(). We can use this method to push a new entry into the browser’s history. It doesn’t need a refresh and will show the new URL in the browser.

The history.pushState() method accepts three arguments:

  • state: This is an object with details about the URL.
  • title: The title (usually the <title> attribute).
  • url: You see the actual URL in your browser bar.

In code, it would look like this:

history.pushState({ pageID: 'unicorn' }, 'Unicorn', '/unicorn');

You can open up the console and paste the above code into it. And you should see the URL change.

Also, note we tell it the title, but it is not reflected anywhere. I’m not 100% sure why we even have the title option.

Browser Support

History support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter