Skip to content

Commit c3ea9d2

Browse files
committed
Allow theme switching without local storage
Protect against a null `window.localStorage` result which can happen if the user has disabled support. Closes gh-50
1 parent bec8633 commit c3ea9d2

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/main/js/setup/switchtheme.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,22 +46,30 @@
4646
}
4747

4848
function isInitialThemeDark() {
49-
return (
50-
localStorage.getItem("theme") === "dark" || prefersDarkColorScheme.matches
51-
);
49+
return loadTheme() === "dark" || prefersDarkColorScheme.matches;
5250
}
5351

5452
function onThemeChange() {
5553
if (this.checked) {
5654
delay(function () {
5755
htmlElement.classList.add("dark-theme");
5856
}, 100);
59-
localStorage.setItem("theme", "dark");
57+
saveTheme("dark");
6058
} else {
6159
delay(function () {
6260
htmlElement.classList.remove("dark-theme");
6361
}, 100);
64-
localStorage.setItem("theme", "light");
62+
saveTheme("light");
63+
}
64+
}
65+
66+
function saveTheme(theme) {
67+
if (localStorage) {
68+
localStorage.setItem("theme", theme);
6569
}
6670
}
71+
72+
function loadTheme() {
73+
return localStorage !== null ? localStorage.getItem("theme") : null;
74+
}
6775
})();

0 commit comments

Comments
 (0)