From 0d281d9de67969a2ae35bfe3c0d81ea8d8d0e9c2 Mon Sep 17 00:00:00 2001 From: Sam Date: Wed, 9 Jul 2014 16:15:52 +1000 Subject: [PATCH] FIX: Firefox chucks exceptions on localStorage with cookies disabled --- .../discourse/lib/key_value_store.js | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/app/assets/javascripts/discourse/lib/key_value_store.js b/app/assets/javascripts/discourse/lib/key_value_store.js index 9808590a5..17d17c76a 100644 --- a/app/assets/javascripts/discourse/lib/key_value_store.js +++ b/app/assets/javascripts/discourse/lib/key_value_store.js @@ -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: "", @@ -16,14 +26,14 @@ 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--; } @@ -31,21 +41,21 @@ Discourse.KeyValueStore = { }, 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]; } };