From a6b609ddb4016522a9f6a9fca73d4463fad46f32 Mon Sep 17 00:00:00 2001 From: Justin Hall Date: Mon, 13 Feb 2023 10:31:12 -0700 Subject: [PATCH] fix: ignore unexpected values in localStorage (#146) --- .changeset/neat-colts-impress.md | 5 +++++ src/gatsby-node.ts | 13 +++++-------- 2 files changed, 10 insertions(+), 8 deletions(-) create mode 100644 .changeset/neat-colts-impress.md 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);