DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on

angular | sync session storage between multiple tabs using local storage event

Who need this?

  • Want to find a solution to sync data in sessionStorage between multiple tabs

Solution

  • Create session storage service ng g s session-storage
// session-storage.service.ts
import { Injectable, OnDestroy } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SessionStorageService implements OnDestroy {
  constructor() {
    window.addEventListener('storage', this.handleStorageEvent, false);

    this.requestSyncSessionStorage();
  }

  handleStorageEvent = (event: StorageEvent): void => {
    if (event.key === 'requestSyncSessionStorage') {
      console.log('handleStorageEvent - requestSyncSessionStorage', event);
      localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
      localStorage.removeItem('sessionStorage');
    } else if (event.key === 'sessionStorage') {
      console.log('handleStorageEvent - sessionStorage', event);
      const sessionStorage = JSON.parse(event.newValue || '{}');
      for (const key in sessionStorage) {
        window.sessionStorage.setItem(key, sessionStorage[key]);
      }
    }
  };

  requestSyncSessionStorage(): void {
    console.log('requestSyncSessionStorage - sessionStorage', sessionStorage);
    if (!sessionStorage.length) {
      const current = new Date().toLocaleTimeString();
      console.log('requestSyncSessionStorage - request', current);
      localStorage.setItem(
        'requestSyncSessionStorage',
        'request session storage' + current
      );
    }
  }

  getToken(): string {
    const tokenStr = window.sessionStorage.getItem('token') || 'null';
    const token = JSON.parse(tokenStr);
    console.log('getToken', token);
    return token;
  }

  setToken(): void {
    const token = {
      username: 'Hey It me',
      token: '123456789',
      timestamp: new Date().toLocaleTimeString(),
    };
    console.log('setToken', token);
    window.sessionStorage.setItem('token', JSON.stringify(token));
  }

  removeToken(): void {
    window.sessionStorage.removeItem('token');
  }

  ngOnDestroy(): void {
    window.removeEventListener('storage', this.handleStorageEvent, false);
  }
}
Enter fullscreen mode Exit fullscreen mode
// app.component.html
<h1>Demo Share data between token storage service</h1>
<button (click)="sessionStorageService.setToken()">Set Token</button>
<button (click)="sessionStorageService.getToken()">Get Token</button>
<button (click)="sessionStorageService.removeToken()">Remove Token</button>
Enter fullscreen mode Exit fullscreen mode
// app.component.ts
import { Component } from '@angular/core';
import { SessionStorageService } from './session-storage.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  constructor(public sessionStorageService: SessionStorageService) {}
}

Enter fullscreen mode Exit fullscreen mode

What are we gonna do?

  • Step 1: Check session storage, if it null or empty => do step 2
  • Step 2: Ask another tab: hey, have you got session storage? > send it to me (using localStorage event)

Top comments (0)