jquery session cookie

jquery session cookie – HTML5 sessionStorage

Posted on: November 5th, 2013 by taff No Comments

 

I've always been a bit reluctant to using HTML5 that isn't globally supported, but recently I've been doing a lot of work on a mobile version of a website which means I get to use everything :-)

Whenever I used to need a jquery session cookie, i.e. a cookie that exists for a session and is accessible via javascript, I would use the excellent jQuery cookie plugin but with the (near) global support for sessionStorage and localStorage I think it will become a thing of the past.

sessionStorage - The HTML5 equivalent of a jquery session cookie

I needed a jquery session cookie to see if someone had already had the geolocation window and if so, surpress it until the next time the user visits the site. I could probably have done this just as quick with the cookie plugin but after taking a look at the sessionStorage support, decided it was the way to go.

jQuery(function () {
var hadLocationWindow = sessionStorage.getItem("hadLocationWindow");

if(hadLocationWindow == null || hadLocationWindow == 'undefined') {
sessionStorage.setItem("hadLocationWindow", "YES");
console.log("no location yet, offer geolocation");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
} else {
console.log("you have seen this window before");
}

});

Viewing SessionStorage and localStorage Data

When it comes to sessionStorage and localStorage (the persistent version of storage), I use a firebug with a simple


console.log(sessionStorage);

normally to see what is happening. If I need to do more I can recommend the FireStorage Plus! Plugin

Another advantage is the ability to save large amounts of data which has no limit to the possibilities such as saving profile data to save querying the database so often thus making it even more useful than the jquery session cookie