diff --git a/.changeset/neat-colts-impress.md b/.changeset/neat-colts-impress.md new file mode 100644 index 0000000..1e6d46e --- /dev/null +++ b/.changeset/neat-colts-impress.md @@ -0,0 +1,5 @@ +--- +'gatsby-plugin-use-dark-mode': patch +--- + +Ignore unexpected values in localStorage. diff --git a/src/gatsby-node.ts b/src/gatsby-node.ts index 5db2e46..8cb705e 100644 --- a/src/gatsby-node.ts +++ b/src/gatsby-node.ts @@ -86,19 +86,16 @@ function generateNoFlashScript({ var preferDarkQuery = '(prefers-color-scheme: dark)'; var mql = window.matchMedia(preferDarkQuery); var supportsColorSchemeQuery = mql.media === preferDarkQuery; - var localStorageTheme = null; + var localStorageValue = null; try { - localStorageTheme = localStorage.getItem(storageKey); + localStorageValue = JSON.parse(localStorage.getItem(storageKey)); } catch (err) {} - var localStorageExists = localStorageTheme !== null; - if (localStorageExists) { - localStorageTheme = JSON.parse(localStorageTheme); - } + var isLocalStorageValueValid = localStorageValue === true || localStorageValue === false; // Determine the source of truth - if (localStorageExists) { + if (isLocalStorageValueValid) { // source of truth from localStorage - setClassOnDocumentBody(localStorageTheme); + setClassOnDocumentBody(localStorageValue); } else if (supportsColorSchemeQuery) { // source of truth from system setClassOnDocumentBody(mql.matches);