JavaScript: History Object

Sahar E.Hassan
Oct 22, 2020
javascript history object

History object:

  • Is a javascript object, contains all visited URLs in specific browser tab.
  • It’s part of window object and can be accessible throw window.history property.
console.log(window.history);
result of logging window.history

History Properties:

1- history.length:

  • It returns the number of the URLs in the session history.

2- history.scrollRestoration:

  • It allows you to set default scroll restoration behavior on history navigation.
  • It has two values either auto or manual.

auto: when you set it to “auto”, the location on the page to which the user has scrolled will be restored.

manual: when you set it to “manual”, the user will have to scroll to the location manually

3- history.state:

  • It returns a value representing the state at the top of the history stack.

History Methods:

1- history.back():

  • It goes back to the previous page in session history (as if the user clicks on back button in the browser).

2- history.forward():

  • It goes to the next page in session history (as if the user clicks on next button in the browser).

3- history.go():

  • It loads a page from the session history, identified by its relative location to the current page (e.g. -1 for the previous page or 1 for the next page).
  • If you call it with an out-of-bounds location (e.g. you give it 1 while ther’s no next page in the session history), It’ll has no effect.
  • If you call it without any parameter or pass 0 to it, it’ll reload the current page.
histoy.back();    ===    history.go(-1);
history.forward(); === history.do(1);
history.go(); === history.go(0) // it reloads current page

I hope you enjoy reading the article, all comments and feedbacks are mostly welcome.

Happy coding!

--

--