Search code examples
javascriptangulariframeonbeforeunloadiframe-app

Angular8 IFrame before beforeunload event


I have an angular application which is kind of the main application that hosts sub application inside it. The sub applications are also angular applications. The way that I load sub application is through Iframes.

The sub-applications are shown as a list and when I click on an tab, that application is loaded. When I am making some changes to the data in an application and if I click on another sub-tab, I wanted to show a warning message saying " changes will be lost". I am able to achieve it by using beforeunload event as below. I can check to see if there are any unsaved changes and show the warning popup.

  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: any) {
      if (**my logic here) {
          $event.returnValue =true;
      }
  }

The only problem with this is, when I click the other sub-tab, the host application highlights that sub-tab and then the warning pop-up is shown. If I click on stay button on the popup, I am able to be on the sub-tab I want but on the host application the other sub-tab is highlighted. So I am trying to see a way to not highlight the other tab if I want to stay on the current sub-tab. Something before beforeunload.


Solution

  • In child app

    const origin = this.getCurrentHostOrigin();
    if (cancelSwitchTab) {
        window.parent.postMessage({}, origin); 
    }
    

    In host app:

    this.renderer.listen(this.windowsRef.nativeWindow, 'message', event => {
      const message = event.data;
      *** your logic to revert highlight to current tab ***
    });