DEV Community

Cover image for Vanilla JavaScript History API
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript History API

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();
Enter fullscreen mode Exit fullscreen mode

The forward() in turn looks like this:

window.history.forward();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

var numberInHistory = window.history.length;
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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 (0)