History

JavaScript History Object is build-in object in frontend javascript. history object is used to check browser session history. The history stored in our browser is access using JavaScript history property of current browser session.

history.length

history.length is a read-only property used to check total histories in current browser session. Minimum value for history.length is 1 and can go up.


    console.log(history.length);
  

JS History Methods


History.back

history.back method is used to go back by one step only. There is no parameter in back method. The limitation of history.back method is that it can go back only one step. See example




    history.back()

History.forward

history.forward method is used to go forward by one step . There is no parameter in forward method. The limitation of history.forward method is that it can go forward only one page. See example




    history.forward()

History.go

history.go method can be used to go back and forward by single or multiple pages. The parameter in go method tell the path. It can be any number, positive, negative or 0 (zero). Zero can reload page, negative can go back and positive can go forward. See examples

History.go examples



    history.go(-1);         // goes back 1 page
    history.go(1);          // goes forward 1 page
    history.go(0);          // refresh current page

History.go for multiple pages



    history.go(-2);         // goes 2 pages back
    history.go(2);          // goes 2 pages forward

history.pushState

history.pushState method is used to add entry to browser session history. The first parameter is state, second is title and third one is url (optional).


  history.pushState( state, title, [url])    
  
Property Value Meaning
state { "name":"new state", "id": 1} js object with key-values
title "new title" a string value. supported by Safari only
url ( optional ) 'test.html' new url without reload

history.pushState example


  var state={ "page":"page1", "id":"id1"};
  var title="new title";
  var url="test.html";

  history.pushState( state, title, url);