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

Even safer local storage... #2686

Merged
merged 2 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading