svelte-syncable icon indicating copy to clipboard operation
svelte-syncable copied to clipboard

Handle Safari SecurityError accessing localStorage

Open aredridel opened this issue 4 years ago • 1 comments

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Safari throws an exception, and I've squashed it to at least this behavior — returning a regular writable might be preferable, but this seemed like a good start.

Here is the diff that solved my problem:

diff --git a/node_modules/svelte-syncable/index.js b/node_modules/svelte-syncable/index.js
index 0b73f0d..df52347 100644
--- a/node_modules/svelte-syncable/index.js
+++ b/node_modules/svelte-syncable/index.js
@@ -3,17 +3,24 @@ import { writable } from 'svelte/store';
 let prefix = 'svelteStore';
 
 const get = (key) => {
-  if (typeof window === undefined || !localStorage) return undefined;
-  const value = localStorage.getItem(key);
-  return value === undefined
-    ? ""
-    : JSON.parse(value);
+  try {
+    if (typeof window === undefined || !localStorage) return undefined;
+    const value = localStorage.getItem(key);
+    return value === undefined ? "" : JSON.parse(value);
+  } catch (e) {
+    if (e.name == 'SecurityError') return undefined;
+    throw e;
+  }
 };
 
 const set = (key, value) => {
-  if (typeof window === undefined || !localStorage) return;
+  try {
+    if (typeof window === undefined || !localStorage) return;
 
-  localStorage.setItem(key, JSON.stringify(value));
+    localStorage.setItem(key, JSON.stringify(value));
+  } catch (e) {
+    if (e.name != 'SecurityError') throw e;
+  }
 };
 
 const syncValue = (key, observable) => {
@@ -38,3 +45,4 @@ export const syncable = (name, value, hydrate = true) => {
 
   return syncValue(key, writable(lastValue));
 };
+

This issue body was partially generated by patch-package.

aredridel avatar Mar 10 '21 18:03 aredridel

Any chance I can get this or another approach to error handling integrated?

aredridel avatar May 21 '21 13:05 aredridel