From 2c5391a154abe80041f391220ee17ba1b85093ca Mon Sep 17 00:00:00 2001
From: Walter Leibbrandt <23798+walterl@users.noreply.github.com>
Date: Tue, 13 Aug 2019 00:02:38 +0200
Subject: [PATCH] Factor out test for access to localStorage (#10533)

* Factor out test for access to localStorage

This allows code that uses localStorage to test against
`window.hasLocalStorage`, in stead of handling exceptions generated when
access to localStorage is denied.

* Move check for localStorage to metabase/lib/dom
---
 frontend/src/metabase/lib/debug.js      |  4 +++-
 frontend/src/metabase/lib/dom.js        | 12 ++++++++++++
 frontend/src/metabase/lib/i18n-debug.js |  4 +++-
 3 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/frontend/src/metabase/lib/debug.js b/frontend/src/metabase/lib/debug.js
index fcacf91b693..af976956e59 100644
--- a/frontend/src/metabase/lib/debug.js
+++ b/frontend/src/metabase/lib/debug.js
@@ -1,8 +1,10 @@
+import { HAS_LOCAL_STORAGE } from "metabase/lib/dom";
+
 let debug;
 if (
   typeof window === "object" &&
   ((window.location && window.location.hash === "#debug") ||
-    (window.localStorage && window.localStorage.getItem("debug")))
+    (HAS_LOCAL_STORAGE && window.localStorage.getItem("debug")))
 ) {
   debug = true;
 } else {
diff --git a/frontend/src/metabase/lib/dom.js b/frontend/src/metabase/lib/dom.js
index d9f7d086a22..74b37c0a574 100644
--- a/frontend/src/metabase/lib/dom.js
+++ b/frontend/src/metabase/lib/dom.js
@@ -26,6 +26,18 @@ export const IFRAMED_IN_SELF = (function() {
   }
 })();
 
+// check if we have access to localStorage to avoid handling "access denied"
+// exceptions
+export const HAS_LOCAL_STORAGE = (function() {
+  try {
+    window.localStorage; // This will trigger an exception if access is denied.
+    return true;
+  } catch (e) {
+    console.warn("localStorage not available:", e);
+    return false;
+  }
+})();
+
 export function isObscured(element, offset) {
   if (!document.elementFromPoint) {
     return false;
diff --git a/frontend/src/metabase/lib/i18n-debug.js b/frontend/src/metabase/lib/i18n-debug.js
index 0699a6896e4..82e3c6bd0d1 100644
--- a/frontend/src/metabase/lib/i18n-debug.js
+++ b/frontend/src/metabase/lib/i18n-debug.js
@@ -1,5 +1,7 @@
 import React from "react";
 
+import { HAS_LOCAL_STORAGE } from "metabase/lib/dom";
+
 // If enabled this monkeypatches `t` and `jt` to return blacked out
 // strings/elements to assist in finding untranslated strings.
 //
@@ -52,6 +54,6 @@ export function enableTranslatedStringReplacement() {
   };
 }
 
-if (window.localStorage && window.localStorage["metabase-i18n-debug"]) {
+if (HAS_LOCAL_STORAGE && window.localStorage["metabase-i18n-debug"]) {
   enableTranslatedStringReplacement();
 }
-- 
GitLab