Skip to content

Handle Safari SecurityError accessing localStorageΒ #11

@aredridel

Description

@aredridel

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions