Fix localStorage crash with securityError

pull/2387/head
Jérémy Rialland 2022-11-14 12:35:17 +01:00 committed by Jérémy Rialland
parent 74a14bf24d
commit 3e30b4c371
3 changed files with 27 additions and 9 deletions

View File

@ -1,21 +1,21 @@
import { useIsEmbedded } from '@/components/utils/useIsEmbedded'
import { getItem, setItem } from '@/storage/safeLocalStorage'
import React, { useEffect } from 'react'
type DarkModeContextType = [boolean, (darkMode: boolean) => void]
const persistDarkMode = (darkMode: boolean) => {
localStorage.setItem('darkMode', darkMode.toString())
setItem('darkMode', darkMode.toString())
}
const getDefaultDarkMode = () => {
if (import.meta.env.SSR) {
return false
}
if (localStorage?.getItem('darkMode')) {
return localStorage.getItem('darkMode') === 'true'
}
return matchMedia?.('(prefers-color-scheme: dark)').matches
return getItem('darkMode')
? getItem('darkMode') === 'true'
: matchMedia?.('(prefers-color-scheme: dark)').matches
}
export const DarkModeContext = React.createContext<DarkModeContextType>([

View File

@ -12,6 +12,7 @@ export function removeItem(key: string) {
return null
}
}
export function getItem(key: string) {
try {
return window.localStorage.getItem(key)
@ -24,6 +25,7 @@ export function getItem(key: string) {
return null
}
}
export function setItem(key: string, value: string) {
try {
return window.localStorage.setItem(key, value)

View File

@ -188,10 +188,26 @@
</div>
<script>
const isIframe = (new URLSearchParams(
document.location.search.substring(1)
).get('iframe'))
const darkMode = window.localStorage && window.localStorage.getItem('darkMode') === 'true' && !isIframe
const isIframe = new URLSearchParams(
document.location.search.substring(1)
).get('iframe')
function getItem(key) {
try {
return window.localStorage.getItem(key)
} catch (error) {
if (error instanceof Error && error.name === 'SecurityError') {
// eslint-disable-next-line no-console
console.warn(
'[localStorage] Unable to set item due to security settings'
)
}
return null
}
}
const darkMode = !isIframe && getItem('darkMode') === 'true'
if (darkMode) {
document.body.style.backgroundColor = '#0f172a'