DEV Community

Cover image for Vanilla JavaScript Update URL without Refresh
Chris Bongers
Chris Bongers

Posted on • Originally published at

Vanilla JavaScript Update URL without Refresh

Today we are looking into updating the URL without doing a refresh. We can make use of the History API to access and modify the URL states.

The cool part, 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.

More on these methods in another article.

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 (normally the <title> attribute)
  • url: The actual URL you see in your browser bar.

In code, it would look like this:

history.pushState({pageID: 'unicorn'}, 'Unicorn', '/unicorn');
Enter fullscreen mode Exit fullscreen mode

You can open up the console and paste the above code in 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

Top comments (5)

ellisgl profile image

And you could send secret message through the address bar.

dailydevtips1 profile image
Chris Bongers

Yes we could! ๐Ÿ‘€

markokolombo profile image
Marko Kolombo

"Note that all browsers but Safari currently ignore the title parameter. "

dailydevtips1 profile image
Chris Bongers

None of the browsers support the title attribute, not even sure why it's an option as mentioned in the article.