Skip to content

Commit 8362aa2

Browse files
committed
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
1 parent d4e2dca commit 8362aa2

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/librustdoc/html/static/storage.js

+20-8
Original file line numberDiff line numberDiff line change
@@ -27,26 +27,38 @@ function onEach(arr, func) {
2727
}
2828

2929
function updateLocalStorage(name, value) {
30-
if (typeof(Storage) !== "undefined") {
31-
try {
32-
window.localStorage;
33-
} catch(err) {
34-
// Storage is supported, but browser preferences deny access to it.
35-
return;
36-
}
30+
if (usableLocalStorage()) {
3731
localStorage[name] = value;
3832
} else {
3933
// No Web Storage support so we do nothing
4034
}
4135
}
4236

4337
function getCurrentValue(name) {
44-
if (typeof(Storage) !== "undefined" && localStorage[name] !== undefined) {
38+
if (usableLocalStorage() && localStorage[name] !== undefined) {
4539
return localStorage[name];
4640
}
4741
return null;
4842
}
4943

44+
function usableLocalStorage() {
45+
// Check if the browser supports localStorage at all:
46+
if (typeof(Storage) === "undefined") {
47+
return false;
48+
}
49+
// Check if we can access it; this access will fail if the browser
50+
// preferences deny access to localStorage, e.g., to prevent storage of
51+
// "cookies" (or cookie-likes, as is the case here).
52+
try {
53+
window.localStorage;
54+
} catch(err) {
55+
// Storage is supported, but browser preferences deny access to it.
56+
return false;
57+
}
58+
59+
return true;
60+
}
61+
5062
function switchTheme(styleElem, mainStyleElem, newTheme) {
5163
var fullBasicCss = "rustdoc" + resourcesSuffix + ".css";
5264
var fullNewTheme = newTheme + resourcesSuffix + ".css";

0 commit comments

Comments
 (0)