Skip to content

Commit

Permalink
Use a fake LocalStorage when the real one is not available. Fixes #308
Browse files Browse the repository at this point in the history
In particular, attempting to use js/localStorage throws an error in
sandboxed iframes, preventing the use of 10x.

delete-all-keys! (called by the factory reset) doesn't work perfectly
with the fake storage, but it doesn't error and a refresh will always
clear the settings.
  • Loading branch information
bshepherdson authored and superstructor committed Jul 5, 2021
1 parent e7105cc commit 6f2ef39
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/day8/re_frame_10x/fx/local_storage.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,22 @@
(:require
[goog.storage.Storage]
[goog.storage.mechanism.HTML5LocalStorage]
[goog.testing.storage.FakeMechanism]
[cljs.reader :as reader]
[clojure.string :as string]
[day8.re-frame-10x.inlined-deps.re-frame.v1v1v2.re-frame.core :as rf]))

(def storage (goog.storage.Storage. (goog.storage.mechanism.HTML5LocalStorage.)))
(def storage-mechanism
"LocalStorage is not available in sandboxed iframes, so check
window.localStorage and use the fake storage mechanism if it's not available.
re-frame-10x settings will not persist, but it will work."
(try
(when js/localStorage
(goog.storage.mechanism.HTML5LocalStorage.))
(catch js/Error _
(goog.testing.storage.FakeMechanism.))))

(def storage (goog.storage.Storage. storage-mechanism))

(def safe-prefix "day8.re-frame-10x.")

Expand All @@ -24,10 +35,16 @@
not-found
(reader/read-string value)))))

(defn- all-keys []
(try
(js/Object.keys js/localStorage)
(catch js/Error _
[])))

(defn delete-all-keys!
"Deletes all re-frame-10x config keys"
[]
(doseq [k (js/Object.keys js/localStorage)]
(doseq [k (all-keys)]
(when (string/starts-with? k safe-prefix)
(.remove storage k))))

Expand All @@ -50,4 +67,4 @@
(fn [coeffects {:keys [key or]}]
(assoc coeffects
(keyword key)
(load key or))))
(load key or))))

0 comments on commit 6f2ef39

Please sign in to comment.