Extract localStorage tests out into a helper method; use in getCurrentValue()

1. Extract the tests for whether or not we have workable localStorage out into
   a helper method, so it can be more easily reused
2. Use it in getCurrentValue() too, for the same reasons, as suggested in code
   review
This commit is contained in:
Roy Wellington Ⅳ 2018-10-15 20:38:51 -07:00
parent d4e2dcaff1
commit 8362aa2178

View file

@ -27,13 +27,7 @@ function onEach(arr, func) {
}
function updateLocalStorage(name, value) {
if (typeof(Storage) !== "undefined") {
try {
window.localStorage;
} catch(err) {
// Storage is supported, but browser preferences deny access to it.
return;
}
if (usableLocalStorage()) {
localStorage[name] = value;
} else {
// No Web Storage support so we do nothing
@ -41,12 +35,30 @@ function updateLocalStorage(name, value) {
}
function getCurrentValue(name) {
if (typeof(Storage) !== "undefined" && localStorage[name] !== undefined) {
if (usableLocalStorage() && localStorage[name] !== undefined) {
return localStorage[name];
}
return null;
}
function usableLocalStorage() {
// Check if the browser supports localStorage at all:
if (typeof(Storage) === "undefined") {
return false;
}
// Check if we can access it; this access will fail if the browser
// preferences deny access to localStorage, e.g., to prevent storage of
// "cookies" (or cookie-likes, as is the case here).
try {
window.localStorage;
} catch(err) {
// Storage is supported, but browser preferences deny access to it.
return false;
}
return true;
}
function switchTheme(styleElem, mainStyleElem, newTheme) {
var fullBasicCss = "rustdoc" + resourcesSuffix + ".css";
var fullNewTheme = newTheme + resourcesSuffix + ".css";