clearSessionStorage
Clears all data from sessionStorage.
1/**
2 * Clears all data from sessionStorage.
3 */
4export function clearSessionStorage(): void {
5 try {
6 sessionStorage.clear();
7 } catch (e) {
8 console.error('Failed to clear sessionStorage:', e);
9 }
10}
Complete Wipe in One Call
Efficiently removes all sessionStorage data without needing to loop through keys.
Built-in Error Safety
Wrapped in a try-catch to avoid crashing the app if sessionStorage is unavailable or blocked.
Useful for Session Reset
Ideal for scenarios requiring a full environment reset - no need to track keys individually.
Tests | Examples
1beforeEach(() => {
2 sessionStorage.clear();
3 jest.clearAllMocks();
4});
5
6test('clearSessionStorage - removes all keys', () => {
7 sessionStorage.setItem('a', '1');
8 sessionStorage.setItem('b', '2');
9 clearSessionStorage();
10 expect(sessionStorage.length).toBe(0);
11});
12
13test('clearSessionStorage - logs error on failure', () => {
14 const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
15 const originalClear = sessionStorage.clear;
16 Object.defineProperty(sessionStorage, 'clear', {
17 value: () => { throw new Error('Failure'); }
18 });
19
20 clearSessionStorage();
21 expect(console.error).toHaveBeenCalled();
22
23 // Restore original method
24 Object.defineProperty(sessionStorage, 'clear', {
25 value: originalClear
26 });
27});
Common Use Cases
User Logout or Session Expiry
Clear all session data to prevent leakage of sensitive or temporary information.
Resetting Application State
Wipe stored session data when reinitializing or reloading the app.
Testing and Debugging
Programmatically clear sessionStorage during automated tests or debugging sessions.
Error Recovery
Wipe potentially corrupted session values to recover from inconsistent application state.