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

2924: Catch SecurityError when accessing localStorage #2974

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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 release-notes/unreleased/2924-security-error.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
issue_key: 2924
show_in_stores: false
platforms:
- web
en: Fix crashes if local storage is not available
75 changes: 75 additions & 0 deletions web/src/hooks/__tests__/useLocalStorage.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { fireEvent, render } from '@testing-library/react'
import React from 'react'

import Button from '../../components/base/Button'
import useLocalStorage from '../useLocalStorage'

describe('useLocalStorage', () => {
const key = 'my_storage_key'
const MockComponent = () => {
const { value, updateLocalStorageItem } = useLocalStorage({ key, initialValue: 0 })
return (
<div>
{value}
<Button label='increment' onClick={() => updateLocalStorageItem(value + 1)}>
Increment
</Button>
</div>
)
}

beforeEach(() => {
jest.clearAllMocks()
localStorage.clear()
})

it('should correctly set initial value and update value', () => {
const { getByText } = render(<MockComponent />)

expect(getByText(0)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('0')

fireEvent.click(getByText('Increment'))

expect(getByText(1)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('1')

fireEvent.click(getByText('Increment'))
fireEvent.click(getByText('Increment'))
fireEvent.click(getByText('Increment'))

expect(getByText(4)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('4')
})

it('should not use initial value if already set', () => {
localStorage.setItem(key, '10')
const { getByText } = render(<MockComponent />)

expect(getByText(10)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('10')

fireEvent.click(getByText('Increment'))

expect(getByText(11)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('11')
})

it('should continue to work even if local storage is not usable', () => {
localStorage.getItem = () => {
throw new Error('SecurityError')
}
localStorage.setItem = () => {
throw new Error('SecurityError')
}
const { getByText } = render(<MockComponent />)

expect(getByText(0)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('0')

fireEvent.click(getByText('Increment'))

expect(getByText(1)).toBeTruthy()
expect(localStorage.getItem(key)).toBe('1')
})
})
26 changes: 21 additions & 5 deletions web/src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useState, useCallback } from 'react'

import { reportError } from '../utils/sentry'

type UseLocalStorageProps<T> = {
key: string
initialValue: T
Expand All @@ -12,17 +14,31 @@ type UseLocalStorageReturn<T> = {

const useLocalStorage = <T>({ key, initialValue }: UseLocalStorageProps<T>): UseLocalStorageReturn<T> => {
const [value, setValue] = useState<T>(() => {
const localStorageItem = localStorage.getItem(key)
if (localStorageItem) {
return JSON.parse(localStorageItem)
try {
const localStorageItem = localStorage.getItem(key)
if (localStorageItem) {
return JSON.parse(localStorageItem)
}
localStorage.setItem(key, JSON.stringify(initialValue))
} catch (e) {
// Try to prevent the following error crashing the app:
// SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
// See #2924
reportError(e)
Comment on lines +24 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 If we want to leave this comment in permanently, then I think we should rephrase it. If not, I guess we should have some kind of reminder to check in a couple of weeks or months if this issue still occurs. Any thoughts?

}
localStorage.setItem(key, JSON.stringify(initialValue))
return initialValue
})

const updateLocalStorageItem = useCallback(
(newValue: T) => {
localStorage.setItem(key, JSON.stringify(newValue))
try {
localStorage.setItem(key, JSON.stringify(newValue))
} catch (e) {
// Try to prevent the following error crashing the app:
// SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
// See #2924
reportError(e)
Comment on lines +37 to +40
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto

}
setValue(newValue)
},
[key],
Expand Down
Loading