Skip to content

Commit 955016c

Browse files
committed
Rollup merge of #55080 - thanatos:fix-localstorage-crash, r=GuillaumeGomez
Detect if access to localStorage is forbidden by the user's browser If the user's cookie/persistent storage setting forbid access to `localStorage`, catch the exception and abort the access. Currently, attempting to use the expand/contract links at the top of the page for structs/consts/etc. fails due to an unhandled error while accessing `localStorage`, if such access is forbidden, as the exception from the failed access propagates all the way out, interrupting the expand/contract. Instead, I would like to degrade gracefully; the access won't happen (the collapse/expand state won't get persisted) but the actual expanding/contracting of the item will go on to succeed. Fixes #55079
2 parents ed68f1a + cbe98ec commit 955016c

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/librustdoc/html/static/storage.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,34 @@ function onEach(arr, func) {
2626
return false;
2727
}
2828

29+
function usableLocalStorage() {
30+
// Check if the browser supports localStorage at all:
31+
if (typeof(Storage) === "undefined") {
32+
return false;
33+
}
34+
// Check if we can access it; this access will fail if the browser
35+
// preferences deny access to localStorage, e.g., to prevent storage of
36+
// "cookies" (or cookie-likes, as is the case here).
37+
try {
38+
window.localStorage;
39+
} catch(err) {
40+
// Storage is supported, but browser preferences deny access to it.
41+
return false;
42+
}
43+
44+
return true;
45+
}
46+
2947
function updateLocalStorage(name, value) {
30-
if (typeof(Storage) !== "undefined") {
48+
if (usableLocalStorage()) {
3149
localStorage[name] = value;
3250
} else {
3351
// No Web Storage support so we do nothing
3452
}
3553
}
3654

3755
function getCurrentValue(name) {
38-
if (typeof(Storage) !== "undefined" && localStorage[name] !== undefined) {
56+
if (usableLocalStorage() && localStorage[name] !== undefined) {
3957
return localStorage[name];
4058
}
4159
return null;

0 commit comments

Comments
 (0)