<< Back to the blog

HTML5 - History Api




By @islamzatary

List of Advanced HTML5 Topics:


History API

Brief about window.history.
window.history.length
window.history.forward()
window.history.back()
window.history.go()

With dynamic Ajax web applications, where the browser updates the page in parts instead of changing location entirely, it’s difficult to give the user a URL to bookmark or share the current application state.

History API - Standard

The HTML5 history API is a standardized way to manipulate the browser history via script. Part of this API — navigating the history — has been available in previous versions of HTML. The new parts in HTML5 include a way to add entries to the browser history, to visibly change the URL in the browser location bar (without triggering a page refresh), and an event that fires when those entries are removed from the stack by the user pressing the browser’s back button.

History API

Why would you manually manipulate the browser location?
The HTML5 history API is actually designed to ensure that URLs continue to be useful in script-heavy web applications.

what does a URL do?
Identifies a unique resource.
You can link to it directly.
Bookmark it
Search engines can index it.

History API

fundamental limitation
Change the URL, even through script, it triggers a roundtrip to the remote web server and a full page refresh.
The HTML5 history API lets you do way tell a browser to change the URL but only download half a page.

History API

A,B Pages Imagine

History API

History API
history.pushState()
The history.pushState() function takes three parameters:
1. state can be any JSON data structure. It is passed back to the popstate event handler, which you’ll learn about in just a moment. We don’t need to track any state in this demo, so I’ve left it as null.

History API

2. title can be any string. This parameter is currently unused by major browsers. If you want to set the page title, you should store it in the state argument and set it manually in your popstate callback.
3. url can be, well, any URL. This is the URL you want to appear in the browser’s location bar.

History API

the history.pushState() function to push a fake URL onto the browser’s history stack, when the user presses the back button, the browser will fire a popstate event on the window object.

Live Example Further reading:
Facebook
History.js, a meta-API for manipulating history in both newer and older browsers

http://caniuse.com/#feat=history

HTML5 - History API




Wrapping up








<< Back to the blog

by @islamzatary