Skip to content

Commit

Permalink
Even safer local storage... (#2686)
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge authored Jan 7, 2025
1 parent c30bc24 commit b0bd871
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/strange-hornets-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'gitbook': patch
---

Even safer localStorage
13 changes: 6 additions & 7 deletions packages/gitbook/src/lib/local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
*/
export function getItem<T>(key: string, defaultValue: T): T {
try {
if (typeof localStorage === 'undefined') {
return defaultValue;
if (typeof localStorage !== 'undefined' && localStorage && 'getItem' in localStorage) {
const stored = localStorage.getItem(key);
return stored ? (JSON.parse(stored) as T) : defaultValue;
}
const stored = localStorage.getItem(key);
return stored ? (JSON.parse(stored) as T) : defaultValue;
return defaultValue;
} catch (error) {
if (error instanceof Error && error.name === 'SecurityError') {
return defaultValue;
Expand All @@ -21,10 +21,9 @@ export function getItem<T>(key: string, defaultValue: T): T {
*/
export function setItem(key: string, value: unknown) {
try {
if (typeof localStorage === 'undefined') {
return;
if (typeof localStorage !== 'undefined' && localStorage && 'setItem' in localStorage) {
localStorage.setItem(key, JSON.stringify(value));
}
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
if (error instanceof Error && error.name === 'SecurityError') {
return;
Expand Down

0 comments on commit b0bd871

Please sign in to comment.