ANGULAR: Preventing users from creating duplicate tabs of the same application

73 views Asked by At

I want to prevent users from duplicating tabs of an application, I am using angular 8.3.29.

This is my code:

ngOnInit() {
    this.handleWindowLoad();
  }
ngOnDestroy(): void {
    this.handleBeforeUnload()
  }
@HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(event: any) {
  this.handleOnReloadClose();
  }
handleWindowLoad() {
     if (this.localStorageService.getSessionItem('windows') === AppConstant.API_CONFIG.SCREENCODES.PURCHASEENQUIRY) {
       this.isscreenenabled = false;
     } else {
       this.localStorageService.addSessionItem('windows', AppConstant.API_CONFIG.SCREENCODES.PURCHASEENQUIRY);
       this.isscreenenabled = true;
    }
  }

  handleBeforeUnload() {
    this.localStorageService.addSessionItem('windows', 'unknown');
  }

  handleOnReloadClose(){
    this.localStorageService.removeSessionItem('windows');
  }

when reloading the page ngOndestroy does not work so I cannot reset the value in the storage. Hostlistener updates the value of the storage when i close or reload the duplicate tab, it should only update the value when the main tab is closed or reloaded. Is there any viable option to prevent users from creating duplicate tabs

1

There are 1 answers

0
Sam Scholefield On

The example below prevents a user from opening a new tab if one already exists, and will focus the existing tab in this case.

The example allows to handle any number of tabs by providing unique tabURL and tabName values. Please be aware that the window references are only stored for the life of the application and would be lost on refresh.


 windowObjectReference: Window | null = null; // global variable

  public navigateToTab(event: MouseEvent): void {
        this.openRequestedTab(tabURL, tabName);
        event.preventDefault();
    }

    // open new tab or use existing if available
    private openRequestedTab(url: string, windowName: string) {
        if (
            this.windowObjectReference === null ||
            this.windowObjectReference.closed
        ) {
            this.windowObjectReference = window.open(url, windowName);
        } else {
            this.windowObjectReference.focus();
        }
    }