HTML5 History API

HTML5 History API not supported

Last event fired: (none)

To test the History API, click through the urls below. Note that none of these urls point to real pages. JavaScript will intercept these clicks, load data and the browser address bar will appear to change - but this is the History API in action!

Use the back and forward buttons in your browser to navigate the history.

Note: since these urls aren't real, refreshing the page will land on an invalid url.

var $ = function (s) { return document.getElementById(s); }, state = $('status'), lastevent = $('lastevent'), urlhistory = $('urlhistory'), examples = $('examples'), output = $('output'), template = '

URL: {url}, name: {name}, location: {location}

', data = { // imagine these are ajax requests :) first : { name: "Remy", location: "Brighton, UK" }, second: { name: "John", location: "San Francisco, USA" }, third: { name: "Jeff", location: "Vancover, Canada" }, fourth: { name: "Simon", location: "London, UK" } }; function reportEvent(event) { lastevent.innerHTML = event.type; } function reportData(data) { output.innerHTML = template.replace(/(:?\{(.*?)\})/g, function (a,b,c) { return data[c]; }); } if (typeof history.pushState === 'undefined') { state.className = 'fail'; } else { state.className = 'success'; state.innerHTML = 'HTML5 History API available'; } addEvent(examples, 'click', function (event) { var title; event.preventDefault(); if (event.target.nodeName == 'A') { title = event.target.innerHTML; data[title].url = event.target.getAttribute('href'); // slightly hacky (the setting), using getAttribute to keep it short history.pushState(data[title], title, event.target.href); reportData(data[title]); } }); addEvent(window, 'popstate', function (event) { var data = event.state; reportEvent(event); reportData(event.state || { url: "unknown", name: "undefined", location: "undefined" }); }); addEvent(window, 'hashchange', function (event) { reportEvent(event); // we won't do this for now - let's stay focused on states /* if (event.newURL) { urlhistory.innerHTML = event.oldURL; } else { urlhistory.innerHTML = "no support for event.newURL/oldURL"; } */ }); addEvent(window, 'pageshow', function (event) { reportEvent(event); }); addEvent(window, 'pagehide', function (event) { reportEvent(event); });
Fork me on GitHub