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 dis-
abled, accessing sessionStorage or localStorage will throw a security error. For this reason, your appli-
cation should check whether it's 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 script.
Alternatively, you could just check for Web Storage support with a try/catch and polyfill support (as
explained in Chapter 12 and somewhat later in this chapter) using JavaScript.
The 15-second tutorial
I'm so confident that you'll understand how to use localStorage
immediately that I've included code below, even before I've
explained how it all works, and I'm certain you'll grok the basics
of Web Storage straightaway!
localStorage.superHero = “Remy”;
localStorage.superVillain = “Bruce”;
// some super hero fight occurs
delete localStorage.superVillain;
// the page is reload, browser restarted - we don't care -
¬ we're superheroes!
alert(“The world's baddest badass is: “ +
¬ localStorage.superHero);
Ye p , i t ' s that simple. If you shut down your browser, reboot
your machine, and go back to the same domain where this
data was set, it would all still be there. You could alert out
the  localStorage.superHero value and it would give you,
of course, Remy!
Search WWH ::




Custom Search