Skip to content

Commit

Permalink
fix: check if localStorage is usable before using it (#558)
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonBerry authored Sep 11, 2024
1 parent 7c4ab3a commit eb460a8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
13 changes: 12 additions & 1 deletion lib/utils/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* A utility class for safely interacting with localStorage.
*/
export class LocalStorage {
static store: Storage | undefined = globalThis.localStorage;
static store: Storage | undefined = ensureLocalStorage();

/**
* Safely get a value from localStorage.
Expand Down Expand Up @@ -51,3 +51,14 @@ export class LocalStorage {
this.store?.removeItem(key);
}
}

function ensureLocalStorage(): Storage | undefined {
try {
const testKey = "__test_localStorage__";
globalThis.localStorage.setItem(testKey, testKey);
globalThis.localStorage.removeItem(testKey);
return globalThis.localStorage;
} catch {
return undefined;
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
"bundlesize": [
{
"path": "./dist/search-insights.min.js",
"maxSize": "3.60 kB"
"maxSize": "3.70 kB"
}
],
"packageManager": "[email protected]"
Expand Down

0 comments on commit eb460a8

Please sign in to comment.