Skip to content

Commit

Permalink
FIX: Firefox chucks exceptions on localStorage with cookies disabled
Browse files Browse the repository at this point in the history
  • Loading branch information
SamSaffron committed Jul 9, 2014
1 parent 9c14385 commit 0d281d9
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions app/assets/javascripts/discourse/lib/key_value_store.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@
@namespace Discourse
@module Discourse
**/


var safeLocalStorage;

try {
safeLocalStorage = localStorage;
} catch(e){
// cookies disabled, we don't care
}

Discourse.KeyValueStore = {
initialized: false,
context: "",
Expand All @@ -16,36 +26,36 @@ Discourse.KeyValueStore = {

abandonLocal: function() {
var i, k;
if (!(localStorage && this.initialized)) {
if (!(safeLocalStorage && this.initialized)) {
return;
}
i = localStorage.length - 1;
i = safeLocalStorage.length - 1;
while (i >= 0) {
k = localStorage.key(i);
k = safeLocalStorage.key(i);
if (k.substring(0, this.context.length) === this.context) {
localStorage.removeItem(k);
safeLocalStorage.removeItem(k);
}
i--;
}
return true;
},

remove: function(key) {
return localStorage.removeItem(this.context + key);
return safeLocalStorage.removeItem(this.context + key);
},

set: function(opts) {
if (!(localStorage && this.initialized)) {
if (!safeLocalStorage && this.initialized) {
return false;
}
localStorage[this.context + opts.key] = opts.value;
safeLocalStorage[this.context + opts.key] = opts.value;
},

get: function(key) {
if (!localStorage) {
if (!safeLocalStorage) {
return null;
}
return localStorage[this.context + key];
return safeLocalStorage[this.context + key];
}
};

0 comments on commit 0d281d9

Please sign in to comment.