Subscribe

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 dive more into the History API and see what other elements we can use.

JavaScript Browser API Back and Forward

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

  • back() is the Same as clicking the back button in the browser
  • forward() is the 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 📖

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 2097 devs and subscribe to my newsletter