Vanilla JavaScript History API

โœ๏ธ

Navigation trough the browser history in JavaScript

29 Jun, 2020 ยท 1 min read

Yesterday we had a brief introduction to the History API, by using the pushState method.

Today we'll be diving more into the History API and see what other elements we can use.

JavaScript Browser API Back and Forward

So instead of refreshing the current URL sometimes, we want to navigate true the history programmatically. The History API has three methods of doing so:

  • back() Same as clicking the back button in the browser
  • forward() Same as clicking the forward button
  • go() We can go to a specific index forward (1) or backward (-1)

In action the back() method looks like this:

window.history.back();

The forward() in turn looks like this:

window.history.forward();

And the go() we can use like this:

window.history.go(-1); // back
window.history.go(1); // forward
window.history.go(0); // refresh
window.history.go(); // refresh

You can determine how many pages are in the history by using the following command:

const numberInHistory = window.history.length;

JavaScript History API replaceState

As we saw we can use pushState to change the current state, we can also use replaceState for this:

history.replaceState({ page: 'unicorn' }, 'Unicorn', '/Unicorn');

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 ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API