Files
30-seconds-of-code/snippets/isSessionStorageEnabled.md
2020-12-31 13:13:47 +02:00

27 lines
650 B
Markdown

---
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
```