Skip to content

Commit e0a3398

Browse files
authored
Merge pull request #576 from alexpermyakov/fix-uncaught-localStorage-exception
Fix uncaught localStorage exception
2 parents 9163f48 + 1c32831 commit e0a3398

File tree

2 files changed

+52
-11
lines changed

2 files changed

+52
-11
lines changed

packages/theme-ui/src/color-modes.js

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,31 @@ import { useThemeUI } from './context'
55
import { createColorStyles } from './custom-properties'
66

77
const STORAGE_KEY = 'theme-ui-color-mode'
8-
const HAS_STORAGE = typeof Storage !== 'undefined'
98

109
const storage = {
11-
get: init =>
12-
(HAS_STORAGE && window.localStorage.getItem(STORAGE_KEY)) || init,
13-
set: value => HAS_STORAGE && window.localStorage.setItem(STORAGE_KEY, value),
10+
get: init => {
11+
try {
12+
return window.localStorage.getItem(STORAGE_KEY) || init
13+
} catch (e) {
14+
console.warn(
15+
'localStorage is disabled and color mode might not work as expected.',
16+
'Please check your Site Settings.',
17+
e
18+
)
19+
}
20+
},
21+
22+
set: value => {
23+
try {
24+
window.localStorage.setItem(STORAGE_KEY, value)
25+
} catch (e) {
26+
console.warn(
27+
'localStorage is disabled and color mode might not work as expected.',
28+
'Please check your Site Settings.',
29+
e
30+
)
31+
}
32+
},
1433
}
1534

1635
export const getMediaQuery = () => {

packages/theme-ui/test/color-modes.js

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ test('renders with color modes', () => {
3737
modes: {
3838
dark: {
3939
text: 'white',
40-
}
41-
}
42-
}
40+
},
41+
},
42+
},
4343
}}>
4444
<Mode />
4545
</ThemeProvider>
@@ -64,8 +64,8 @@ test('renders with initial color mode name', () => {
6464
colors: {
6565
modes: {
6666
dark: {},
67-
}
68-
}
67+
},
68+
},
6969
}}>
7070
<Mode />
7171
</ThemeProvider>
@@ -212,8 +212,8 @@ test('inherits color mode state from parent context', () => {
212212
colors: {
213213
modes: {
214214
dark: {},
215-
}
216-
}
215+
},
216+
},
217217
}}>
218218
<ThemeProvider
219219
theme={{
@@ -518,3 +518,25 @@ test('raw color values are passed to theme-ui context when custom properties are
518518
)
519519
expect(color).toBe('tomato')
520520
})
521+
522+
test('warns when localStorage is disabled', () => {
523+
Object.defineProperty(window, 'localStorage', {
524+
get: jest.fn(() => {
525+
throw 'SecurityError: The operation is insecure.'
526+
}),
527+
})
528+
529+
let mode
530+
const Consumer = props => {
531+
const [colorMode] = useColorMode()
532+
mode = colorMode
533+
return false
534+
}
535+
536+
render(
537+
<ThemeProvider>
538+
<Consumer />
539+
</ThemeProvider>
540+
)
541+
expect(mode).toBe('default')
542+
})

0 commit comments

Comments
 (0)