How to implement history plugin in single page application

Posted By Shiv Kumar | 07-Jul-2014

I had a requirement to implement history plugin to support back button functionality in my project.

I have used HTML5 history plugin along with localStorage to store data as browser has not so much space to store and handle mass data.


Advantage of localStorage :

As I have to store the exact state of page so it was necessary for me to store the each update on the page so that on backtrack the exact state can be recieved and localStorage gave me that facilty.



1. History.js You can get it from


Way to use history plugin to push state to History :

History.pushState(data, "title", "url");

e.g : History.pushState({state:1}, "State 1", "?state=1"); 

My all action returns json data so I put each data in localStorage like :

$.localStorage('styles',data);  // here "style" is key and "data" is JSON content got in ajax response.

and way to recieve that data again is :

var State = History.getState();  // state stored
var data = $.localStorage(State.title)  // title in this cas is "styles".

Generally when state of page change then history plugin works using its "window.onstatechange" event. We can use this like :

        var State = History.getState(); // Note: We are using History.getState() instead of event.state


It also provides some function like :

1. History.back()   // Go back once through the history.

2. History.forward()   //Go forward once through the history.

3. History.go(X)    //If X is negative go back through history X times, if X is positive go forwards through history X times1.


ReplaceState in place of pushState :

Sometimes it is required that we have to perform some ajax operations of the crrent accessed page.In this case replacestate is used instead of puh state as it replace the currently pushed state with the new new so that on backtrack you can get exact state.It has the same syntaxlike pushState:


Replaces the existing state with a new state to the browser. data can be null or an object, title can be null or a string, url must be a string



Shiv Kumar

Request for Proposal

Recaptcha is required.

Sending message..