HTML5 PushState

mtrpcic edited this page Jul 31, 2011 · 3 revisions

As of version 0.7, PathJS officially supports the HTML5 History API via pushState. Before reading this page, please make sure you've read the wiki page about Getting Started. The HTML5 History API is only supported by some modern browsers.

Differences with the Hashtag

  • There is no support for root routes or default routes, as these don't make sense when the URI contains no special characters. Simply pass the full route around.
  • Rather than calling the Path.listen() method, you now call the Path.history.listen() method
  • To trigger an event, call the Path.history.pushState method, rather than the history.pushState method.

Defining Routes

You define the routes the same as usual, except you omit the Hashtag from your route:"/html5/rocks").to(function(){
    alert("Hello, World!");

Executing Routes

Much like the regular HTML5 History API, to add a new history item to the global history object, you need to call the pushState method. When you want to use the PathJS Route Dispatcher, you need to call the PathJS pushState method.

Path.history.pushState(state, title, path);

The Path.history.pushState method is analogous to the standard history.pushState method, but wraps calls to the PathJS dispatcher. You can access the history state information the same as if you had manually set the state via history.pushState.

Listen Carefully & Graceful Degredation

As mentioned above, you now need to call the Path.history.listen() method instead of the standard Path.listen() method. Unlike the standard Path.listen() method, this method accepts a single boolean parameter, which tells the PathJS library whether or not it should fallback to hashtag support if HTML5 is not supported.

Path.history.listen(true);  // Yes, please fall back to hashtags if HTML5 is not supported.
Path.history.listen(false); // No, do not fall back to hashtags.
Path.history.listen();      // This is the same as passing "false".

This new method does several things:

  1. Checks to see if HTML5 is supported, and sets the Path.history.supported attribute accordingly
  2. Assigns internal methods to the window.onpopstate attribute to provide 'back' capabilities
  3. Checks, depending on the fallback parameter, whether or not to invoke the hashtag listener and to modify your defined routes to support hashtags.


  • The Path.history.listen() method will wrap a call to Path.listen() if you want gracefull degredation to Hashtags. There is no need for you to call it yourself in this case.
  • PathJS only provides wrappers for the HTML5 History API, and as such, the HTML5 support is only available in modern browsers that support the HTML5 History API.