Home > OS >  Communicate between base window and popup window Angular 12
Communicate between base window and popup window Angular 12

Time:04-04

I need to trigger some event from the base window to a popup window when a user tries to open the same popup window again, which is a gear icon action. What are the different ways I can approach this use case? I tried using a service but since the base window and popup window are different angular applications, it's creating a different instance of the service. Please guide me through the different possible ways to make this possible. Thanks.

import { Injectable } from "@angular/core";
import { Subject, ReplaySubject } from "rxjs";

@Injectable()
export class CommunicatingService {
  subscribers: any = [];
  private subject = new Subject<any>();
  sub = this.subject.asObservable();
  a: any = [];
  constructor() {}

  nextSub(data: any) {
    this.subject.next(data)
  }
}

CodePudding user response:

Solutions:

  1. If your two applications are deployed in the same domain, use browser storage(local storage or others) to store the information. Set a flag in local storage
window.localStorage.setItem("isPopOpen", "true");

Get the flag from local storage

window.localStorage.getItem("isPopOpen");
  1. If your applications are hosted on different domains, use Window.postMessage() to communicate. The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

More on window.postMessage() here https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

CodePudding user response:

Change your service code like below:

@Injectable({
  providedIn: 'root'
})

This will make the service singleton.

  • Related