Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
sessionStorage polyfill
/*
* Based on: http://www.quirksmode.org/js/cookies.html
* and https://github.com/wojodesign/local-storage-js/blob/master/storage.js
* and https://gist.github.com/350433
* License: http://www.opensource.org/licenses/MIT
*/
(function(window) {
'use strict';
window.sessionStorage = window.sessionStorage || {
length: 0,
setItem: function(key, value) {
document.cookie = key + '=' + value + '; path=/';
this.length++;
},
getItem: function(key) {
var keyEQ = key + '=';
var ca = document.cookie.split(';');
for (var i = 0, len = ca.length; i < len; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(keyEQ) === 0) return c.substring(keyEQ.length, c.length);
}
return null;
},
removeItem: function(key) {
this.setItem(key, '', -1);
this.length--;
},
clear: function() {
// Caution: will clear all persistent cookies as well
var ca = document.cookie.split(';');
for (var i = 0, len = ca.length; i < len; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
var key = c.substring(0, c.indexOf('='));
this.removeItem(key);
}
this.length = 0;
},
key: function(n) {
var ca = document.cookie.split(';');
if (n >= ca.length || isNaN(parseFloat(n)) || !isFinite(n)) return null;
var c = ca[n];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
return c.substring(0, c.indexOf('='));
}
};
})(this);
@miketaylr

This comment has been minimized.

Show comment Hide comment
@miketaylr

miketaylr Jun 6, 2012

Does it stick around after the session has ended?

Does it stick around after the session has ended?

@tagawa

This comment has been minimized.

Show comment Hide comment
@tagawa

tagawa Jun 7, 2012

Not in my testing. They're cookies without an expiry date, so they (should) die when the browser closes.
For persistent storage, this localStorage polyfill seems to work well:
https://github.com/wojodesign/local-storage-js/blob/master/storage.js

Owner

tagawa commented Jun 7, 2012

Not in my testing. They're cookies without an expiry date, so they (should) die when the browser closes.
For persistent storage, this localStorage polyfill seems to work well:
https://github.com/wojodesign/local-storage-js/blob/master/storage.js

@miketaylr

This comment has been minimized.

Show comment Hide comment
@miketaylr

miketaylr Jun 7, 2012

Nice!

Nice!

@zottto

This comment has been minimized.

Show comment Hide comment
@zottto

zottto Aug 16, 2012

Firefox 14 tells me "TypeError: setting a property that has only a getter, key: function(n) {" when loading the script. Any ideas?

zottto commented Aug 16, 2012

Firefox 14 tells me "TypeError: setting a property that has only a getter, key: function(n) {" when loading the script. Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment