isSessionStorageAvailable
Checks if sessionStorage is available and functional.
1/**
2 * Checks if sessionStorage is available and functional.
3 *
4 * @returns True if sessionStorage is accessible and writable, false otherwise.
5 */
6export function isSessionStorageAvailable(): boolean {
7 try {
8 const testKey = '__sessionStorageTest__';
9 sessionStorage.setItem(testKey, 'test');
10 sessionStorage.removeItem(testKey);
11 return true;
12 } catch {
13 return false;
14 }
15}
Robust Environment Check
Validates both access and writability of
sessionStorage
, ensuring it's not just present but functional.Cross-Browser Reliability
Guards against scenarios where storage is disabled (e.g., in incognito mode or strict browser privacy settings).
Fails Gracefully
Uses a try-catch mechanism to safely detect storage availability without throwing unhandled errors.
Lightweight and Fast
Performs a minimal write-read-delete cycle with negligible performance impact.
Tests | Examples
1test('returns true when sessionStorage is available', () => {
2 expect(isSessionStorageAvailable()).toBe(true);
3});
4
5test('returns false when sessionStorage throws', () => {
6 const originalSetItem = Storage.prototype.setItem;
7 Storage.prototype.setItem = () => {
8 throw new Error('sessionStorage unavailable');
9 };
10
11 expect(isSessionStorageAvailable()).toBe(false);
12
13 Storage.prototype.setItem = originalSetItem;
14});
Common Use Cases
Feature Fallbacks
Determine whether to use
sessionStorage
or fallback to in-memory alternatives.Pre-check Before Storage Operations
Avoid runtime exceptions by verifying support before calling read/write methods.
Testing and Debugging Tools
Ensure storage mechanisms are functional in test environments or automated setups.
Conditional UI Behavior
Disable or hide features that rely on session persistence when
sessionStorage
is unavailable.