hakk

software development, devops, and other drivel
Tree lined path

Update Browser URL Without Page Reload (JavaScript)

When building a single page web app it’s important to update the URLs without refreshing or reloading the page. This will also enable the user to easily copy and share or revisit the current page.

Using the History API

Browsers provide a History API that allows the page URL to be updated that works great for this use case. The API does allow for sharing other data but has limitations; with that in mind it would be better to find another way to share any data especially if it’s sizable.

Here’s an example of the history.pushState method. It accepts three arguments:

  • state: is an object which is associated with the new history entry. A copy of this data is returned by the popstate event.
  • unused: This used to be used as the title of the new page but is no longer used. However, it is still required.
  • url: This is the URL that will be in the new history as well as the browser URL bar. The browser won’t try to load this URL but may try to load the URL later. For example on a page reload, future visit, etc.
history.pushState({msg: 'hello'}, '', '/page2');

Check out a demo of the history.pushState() method combined with popstate.

Open demo in new tab

Reference