Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Safari SecurityError accessing localStorage #11

Open
aredridel opened this issue Mar 10, 2021 · 1 comment
Open

Handle Safari SecurityError accessing localStorage #11

aredridel opened this issue Mar 10, 2021 · 1 comment

Comments

@aredridel
Copy link

Hi! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Today I used patch-package to patch svelte-syncable@1.0.4 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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant