mirror of
https://github.com/Yidadaa/ChatGPT-Next-Web.git
synced 2025-08-08 21:44:59 +08:00
fix: safaLocalStorage
This commit is contained in:
60
app/utils.ts
60
app/utils.ts
@@ -318,3 +318,63 @@ export function adapter(config: Record<string, unknown>) {
|
||||
: path;
|
||||
return fetch(fetchUrl as string, { ...rest, responseType: "text" });
|
||||
}
|
||||
|
||||
export function safeLocalStorage(): {
|
||||
getItem: (key: string) => string | null;
|
||||
setItem: (key: string, value: string) => void;
|
||||
removeItem: (key: string) => void;
|
||||
clear: () => void;
|
||||
} {
|
||||
let storage: Storage | null;
|
||||
|
||||
try {
|
||||
if (typeof window !== "undefined" && window.localStorage) {
|
||||
storage = window.localStorage;
|
||||
} else {
|
||||
storage = null;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("localStorage is not available:", e);
|
||||
storage = null;
|
||||
}
|
||||
|
||||
return {
|
||||
getItem(key: string): string | null {
|
||||
if (storage) {
|
||||
return storage.getItem(key);
|
||||
} else {
|
||||
console.warn(
|
||||
`Attempted to get item "${key}" from localStorage, but localStorage is not available.`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
setItem(key: string, value: string): void {
|
||||
if (storage) {
|
||||
storage.setItem(key, value);
|
||||
} else {
|
||||
console.warn(
|
||||
`Attempted to set item "${key}" in localStorage, but localStorage is not available.`,
|
||||
);
|
||||
}
|
||||
},
|
||||
removeItem(key: string): void {
|
||||
if (storage) {
|
||||
storage.removeItem(key);
|
||||
} else {
|
||||
console.warn(
|
||||
`Attempted to remove item "${key}" from localStorage, but localStorage is not available.`,
|
||||
);
|
||||
}
|
||||
},
|
||||
clear(): void {
|
||||
if (storage) {
|
||||
storage.clear();
|
||||
} else {
|
||||
console.warn(
|
||||
"Attempted to clear localStorage, but localStorage is not available.",
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
Reference in New Issue
Block a user