History API: Navigating the history

We use the methods:

  • back()
  • forward()
  • go()

Let’s start with the simplest thing you can do with the History API.

Go back to the previous page:

history.back()

this goes to the previous entry in the session history. You can forward to the next page using

history.forward()

This is exactly just like using the browser back and forward buttons.

go() lets you navigate back or forward multiple levels deep. For example

history.go(-1) //equivalent to history.back()
history.go(-2) //equivalent to calling history.back() twice
history.go(1) //equivalent to history.forward()
history.go(3) //equivalent to calling history.forward() 3 times

To know how many entries there are in the history, you can call

history.length

Lessons in this unit:

0: Introduction
1: ▶︎ Navigating the history
2: Add an entry to the history
3: Modify history entries
4: Access the current history entry state
5: The `popstate` event
6: The `hashchange` event
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!