about summary refs log tree commit diff
diff options
context:
space:
mode:
authorkennytm <kennytm@gmail.com>2018-10-18 10:47:26 +0800
committerkennytm <kennytm@gmail.com>2018-10-18 12:54:57 +0800
commit955016c79cce334e38305add31703bcf4baeb9d8 (patch)
treefb9c5f48d958c18754eb98cf2e2329080d852df7
parented68f1a5aa24350b0f38988a9a6d86301cd95166 (diff)
parentcbe98ec803c023deb6d200b6761acd7c7d73254c (diff)
downloadrust-955016c79cce334e38305add31703bcf4baeb9d8.tar.gz
rust-955016c79cce334e38305add31703bcf4baeb9d8.zip
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
-rw-r--r--src/librustdoc/html/static/storage.js22
1 files changed, 20 insertions, 2 deletions
diff --git a/src/librustdoc/html/static/storage.js b/src/librustdoc/html/static/storage.js
index 4ef8349fa9c..e10e330402f 100644
--- a/src/librustdoc/html/static/storage.js
+++ b/src/librustdoc/html/static/storage.js
@@ -26,8 +26,26 @@ function onEach(arr, func) {
     return false;
 }
 
+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 updateLocalStorage(name, value) {
-    if (typeof(Storage) !== "undefined") {
+    if (usableLocalStorage()) {
         localStorage[name] = value;
     } else {
         // No Web Storage support so we do nothing
@@ -35,7 +53,7 @@ function updateLocalStorage(name, value) {
 }
 
 function getCurrentValue(name) {
-    if (typeof(Storage) !== "undefined" && localStorage[name] !== undefined) {
+    if (usableLocalStorage() && localStorage[name] !== undefined) {
         return localStorage[name];
     }
     return null;