FIX: Firefox chucks exceptions on localStorage with cookies disabled

This commit is contained in:
Sam 2014-07-09 16:15:52 +10:00
parent 9c14385a86
commit 0d281d9de6

View file

@ -5,6 +5,16 @@
@namespace Discourse @namespace Discourse
@module Discourse @module Discourse
**/ **/
var safeLocalStorage;
try {
safeLocalStorage = localStorage;
} catch(e){
// cookies disabled, we don't care
}
Discourse.KeyValueStore = { Discourse.KeyValueStore = {
initialized: false, initialized: false,
context: "", context: "",
@ -16,14 +26,14 @@ Discourse.KeyValueStore = {
abandonLocal: function() { abandonLocal: function() {
var i, k; var i, k;
if (!(localStorage && this.initialized)) { if (!(safeLocalStorage && this.initialized)) {
return; return;
} }
i = localStorage.length - 1; i = safeLocalStorage.length - 1;
while (i >= 0) { while (i >= 0) {
k = localStorage.key(i); k = safeLocalStorage.key(i);
if (k.substring(0, this.context.length) === this.context) { if (k.substring(0, this.context.length) === this.context) {
localStorage.removeItem(k); safeLocalStorage.removeItem(k);
} }
i--; i--;
} }
@ -31,21 +41,21 @@ Discourse.KeyValueStore = {
}, },
remove: function(key) { remove: function(key) {
return localStorage.removeItem(this.context + key); return safeLocalStorage.removeItem(this.context + key);
}, },
set: function(opts) { set: function(opts) {
if (!(localStorage && this.initialized)) { if (!safeLocalStorage && this.initialized) {
return false; return false;
} }
localStorage[this.context + opts.key] = opts.value; safeLocalStorage[this.context + opts.key] = opts.value;
}, },
get: function(key) { get: function(key) {
if (!localStorage) { if (!safeLocalStorage) {
return null; return null;
} }
return localStorage[this.context + key]; return safeLocalStorage[this.context + key];
} }
}; };