From 7a31b979a09a4d99199fc8351e8b95866eaf40b2 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 31 Dec 2020 13:13:47 +0200 Subject: [PATCH] Add storage testers --- snippets/isLocalStorageEnabled.md | 26 ++++++++++++++++++++++++++ snippets/isSessionStorageEnabled.md | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 snippets/isLocalStorageEnabled.md create mode 100644 snippets/isSessionStorageEnabled.md diff --git a/snippets/isLocalStorageEnabled.md b/snippets/isLocalStorageEnabled.md new file mode 100644 index 000000000..204b96c4e --- /dev/null +++ b/snippets/isLocalStorageEnabled.md @@ -0,0 +1,26 @@ +--- +title: isLocalStorageEnabled +tags: browser,intermediate +--- + +Checks if `localStorage` is enabled. + +- Use a `try...catch` block to return `true` if all operations complete successfully, `false` otherwise. +- Use `Storage.setItem()` and `Storage.removeItem()` to test storing and deleting a value in `window.localStorage`. + +```js +const isLocalStorageEnabled = () => { + try { + const key = `__storage__test`; + window.localStorage.setItem(key, null); + window.localStorage.removeItem(key); + return true; + } catch (e) { + return false; + } +}; +``` + +```js +isLocalStorageEnabled(); // true, if localStorage is accessible +``` diff --git a/snippets/isSessionStorageEnabled.md b/snippets/isSessionStorageEnabled.md new file mode 100644 index 000000000..9aaca6aac --- /dev/null +++ b/snippets/isSessionStorageEnabled.md @@ -0,0 +1,26 @@ +--- +title: isSessionStorageEnabled +tags: browser,intermediate +--- + +Checks if `sessionStorage` is enabled. + +- Use a `try...catch` block to return `true` if all operations complete successfully, `false` otherwise. +- Use `Storage.setItem()` and `Storage.removeItem()` to test storing and deleting a value in `window.sessionStorage`. + +```js +const isSessionStorageEnabled = () => { + try { + const key = `__storage__test`; + window.sessionStorage.setItem(key, null); + window.sessionStorage.removeItem(key); + return true; + } catch (e) { + return false; + } +}; +``` + +```js +isSessionStorageEnabled(); // true, if sessionStorage is accessible +```