Skip to content

Commit

Permalink
fix: be resilient against missing or disabled localStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
josdejong committed Apr 6, 2022
1 parent f0506bd commit 52f76b7
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/lib/utils/debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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
*
Expand Down

0 comments on commit 52f76b7

Please sign in to comment.