What is the History API?
Learn the basics of working with the browser session history and the history object.
What is the History API?
The browser's session history is an ordered list of the pages you have visited. You reach it through the window.history object. The History API is the standard way to work with this history.
console.log(history.length);
history.back();The history object offers methods to add entries, change the current entry, and move back and forward. The most common ones are back(), forward(), go() and the length property.
Navigation methods
history.length gives the number of entries in the session history. In a fresh tab with a single page it is 1.
console.log(history.length);
history.back();
history.forward();
history.go(-2);back() goes one step back, forward() goes one step forward. go(n) jumps n steps forward (positive) or back (negative); go(0) reloads the page.
Exercise Call the navigation methods
Log history.length with console.log. Then write the calls history.back(), history.forward() and history.go(-2).
Show example solution
console.log(history.length);
history.back();
history.forward();
history.go(-2);
Test yourself
-
Which object represents the browser session history?
- window.location
- window.navigator
- window.history
- window.screen
Show answer
window.history — Correct! window.history represents the session history.
-
Go one step back
// go one step back ____;Show answer
// go one step back history.back(); -
Match the history methods
- history.back()
- one step back
- history.forward()
- one step forward
- history.go(-2)
- two steps back
- history.length
- entry count