HTML and CSS Reference
In-Depth Information
function handleStorage(event) {
event = event || window.event; // support IE8
if (event.newValue === null) { // it was removed
stopPlaying();
} else {
// start playing and update display
startPlaying(event.newValue);
}
}
window.addEventListener('storage', handleStorage, false);
window.attachEvent('storage', handleStorage);
Obviously there are more uses than radio, but the potential of
storage events is the ability for completely separate windows on
your domain to speak to each other, something that in the past
would have been very fiddly indeed.
Fallback options
As the storage API is relatively simple, it's possible to replicate
its functionality using alternative JavaScript methods, which
could be useful if the storage API is unavailable.
For
localStorage
, you could use cookies, or for better support
you could use the browser specific
userData
methods or even a
Flash object. For
sessionStorage
, you can use a polyfill that makes
use of the
name
property on the
window
object. The following list-
ing shows how you could replicate most of
sessionStorage
's
functionality (and ensure the data remains locked to the current
window, rather than leaking as cookies would) by manually imple-
menting each of the Storage API methods. Note that the following
code expects that you have JSON support in the browser, either
natively or by loading Douglas Crockford's library.
if (typeof sessionStorage === 'undefined') {
sessionStorage = (function () {
var data = window.top.name ? JSON.parse(window.top..
¬ name) : {};
NoTE
If you want to find
out about polyfills, head
over to Chapter 12; we'll wait
here until you're done.
return {
clear: function () {
data = {};
window.top.name = '';
},