HTML and CSS Reference
In-Depth Information
Watch out for Firefox cookie security
Firefox implements slightly different security around access to session and local storage: If cookies are
disabled, accessing
sessionStorage
or
localStorage
will throw a security error. In this case, you need
to check whether you're able to set cookies before trying to access either of these two storage APIs.
var cookiesEnabled = (function () {
// the id is our test value
var id = new Date().getTime();
// generate a cookie to probe cookie access
document.cookie = '__cookieprobe=' + id + ';path=/';
// if the cookie has been set, then we're good
return (document.cookie.indexOf(id) !== -1);
})();
This code tries to set a cookie and then immediately read it back again. If it fails to read the cookie, it
means that security is blocking you from writing and therefore you can't access the
sessionStorage
or
localStorage
. If cookies aren't enabled, the implications are that reading from
sessionStorage
or
localStorage
will cause a security warning and break your JavaScript.
An overview of the API
Since both the
sessionStorage
and
localStorage
descend from
the Web Storage API, they both have the exact same API (from
the specifi cation):
readonly attribute unsigned long length;
getter DOMString key(in unsigned long index);
getter any getItem(in DOMString key);
setter creator void setItem(in DOMString key, in any data);
deleter void removeItem(in DOMString key);
void clear();
This API makes setting and getting data very easy. The
setItem
method simply takes a key and a value. The
getItem
method
takes the key of data you want and returns the content, as
shown here:
sessionStorage.
setItem
('twitter', '@rem');
alert( sessionStorage.
getItem
('twitter') ); // shows @rem
It's worth noting that in all the latest browsers the
getItem
doesn't return “any” data type. The browsers convert the data
type to a string regardless of what's going in. This is important