Zeo
Zeo

Reputation: 155

window.postMessage to popups in Angular

What I want to do: opening an popup and send the postMessage when the popup is ready.

Problem: I ran into Race Condition which the popup is not ready but the message is sent. I tried to listen to the "INIT" message and in the popup send back message. But the problem is when network latency or some slow computer will not receive the initial message.

The setTimeout obviously not a good solution

Code I have problem with: Parent Window

    const windowFeatures  = "height=800,width=1280,toolbar=1,menubar=1,location=1"; 
    const printWindow = window.open("/print", "Print_Me", windowFeatures);

    setTimeout(() => {printWindow.postMessage({printPageStatus: "INIT"}, window.origin)}, 1000)

    window.addEventListener("message", (event) => { 
      if(event.origin !== window.origin)  return;  
      if(event.data.printPageStatus === "READY") {
        printWindow.postMessage({message: "from parent", window.origin);
        return;
      }
    });

The popup window

 constructor() {
    window.addEventListener("message", event => {
      if(event.origin !== window.origin)  return;    
      if(event.data.printPageStatus === "INIT")
        this.sendReadyConfirmation(event);
      if(event.data.message === "from parent") {
        this.processMessages(event.data);
      }
    }, false);
 }

  sendReadyConfirmation(e): void {
    e.source.postMessage({printPageStatus: "READY"}, e.origin);
  }

Thank you

Upvotes: 0

Views: 2538

Answers (1)

Ritesh Waghela
Ritesh Waghela

Reputation: 3727

What you need to do is send the message when the window has loaded successfully :

const printWindow = window.open("/print", "Print_Me", windowFeatures);
 printWindow.onload = () => {
   printWindow.postMessage({printPageStatus: "INIT"}, window.origin)
};

Upvotes: 1

Related Questions