Add storage testers
This commit is contained in:
26
snippets/isLocalStorageEnabled.md
Normal file
26
snippets/isLocalStorageEnabled.md
Normal file
@ -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
|
||||||
|
```
|
||||||
26
snippets/isSessionStorageEnabled.md
Normal file
26
snippets/isSessionStorageEnabled.md
Normal file
@ -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
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user