From 52f76b73b8d26ffcfca4e8391a55273f5b1d9b22 Mon Sep 17 00:00:00 2001 From: Jos de Jong Date: Wed, 6 Apr 2022 12:43:37 +0200 Subject: [PATCH] fix: be resilient against missing or disabled localStorage --- src/lib/utils/debug.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/lib/utils/debug.js b/src/lib/utils/debug.js index 53a7ba3e..fc261c69 100644 --- a/src/lib/utils/debug.js +++ b/src/lib/utils/debug.js @@ -24,10 +24,7 @@ * @param {boolean} [enabled] * @returns {function (...args: any) : void} */ -export function createDebug( - namespace, - enabled = typeof window !== 'undefined' && window.localStorage['debug'] -) { +export function createDebug(namespace, enabled = tryReadLocalStorage['debug']) { if (enabled) { const color = selectColor(namespace) @@ -41,6 +38,22 @@ export function createDebug( function noop() {} +/** + * Try read a specific key from localStorage + * @param {string} key + * @returns {string | undefined} + */ +function tryReadLocalStorage(key) { + try { + if (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') { + // reading local storage can fail for example because of security restrictions + return window.localStorage[key] + } + } catch (error) { + // we do nothing with the error, not needed in this specific case + } +} + /** * Selects a color for a debug namespace *