mirror of
https://github.com/facebook/docusaurus.git
synced 2025-06-03 11:22:30 +02:00
fix(v2): fail-safe usage of browser storage (localStorage/sessionStorage) when access is denied (#4501)
* fix: Fix unsafe uses of localStorage Puts all uses of localStorage behind an abstraction which doesn't fail when localStorage isn't available. * cleanup fail-safe browser storage usage Co-authored-by: slorber <lorber.sebastien@gmail.com>
This commit is contained in:
parent
cbb31783d7
commit
2c57f44bd6
8 changed files with 160 additions and 52 deletions
|
@ -7,6 +7,7 @@
|
|||
|
||||
import {useState, useCallback, useEffect} from 'react';
|
||||
import type {useTabGroupChoiceReturns} from '@theme/hooks/useTabGroupChoice';
|
||||
import {createStorageSlot, listStorageKeys} from '@docusaurus/theme-common';
|
||||
|
||||
const TAB_CHOICE_PREFIX = 'docusaurus.tab.';
|
||||
|
||||
|
@ -15,21 +16,16 @@ const useTabGroupChoice = (): useTabGroupChoiceReturns => {
|
|||
readonly [groupId: string]: string;
|
||||
}>({});
|
||||
const setChoiceSyncWithLocalStorage = useCallback((groupId, newChoice) => {
|
||||
try {
|
||||
localStorage.setItem(`${TAB_CHOICE_PREFIX}${groupId}`, newChoice);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
createStorageSlot(`${TAB_CHOICE_PREFIX}${groupId}`).set(newChoice);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const localStorageChoices = {};
|
||||
for (let i = 0; i < localStorage.length; i += 1) {
|
||||
const storageKey = localStorage.key(i) as string;
|
||||
for (const storageKey of listStorageKeys()) {
|
||||
if (storageKey.startsWith(TAB_CHOICE_PREFIX)) {
|
||||
const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length);
|
||||
localStorageChoices[groupId] = localStorage.getItem(storageKey);
|
||||
localStorageChoices[groupId] = createStorageSlot(storageKey).get();
|
||||
}
|
||||
}
|
||||
setChoices(localStorageChoices);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue