Search code examples
javascriptpostmessage

Synchronous postMessage


Is there a way to make postMessage "a synchronous call"? meaning:

  • do postMessage from parent to iFrame
  • wait until parent gets back a message (sent from the iFrame)

For example:

function doSomething() {
   targetiFrame.postMessage('actionA');
   handleMessage('actionA').then(function() {
      return true;
   });
}

function handleMessage(action) {
   return new Promise(function(resolve, reject) {
   });
}

Of course, this will not work as I trigger handleMessage while it should be triggered only when the right message received. Is there a way to wait until 'actionA' message received and only then end the function with return true?


Solution

  • I solved the problem like this:

    let doSomethingResolveCallback;
    let doSomethingRejectCallback;
    
    function doSomething() {
      return new Promise(resolve, reject) => {
        doSomethingResolveCallback = resolve;
        doSomethingRejectCallback = reject;
        targetiFrame.postMessage('actionA');
      }
    }
    
    // handles messages from the iFrame
    function handleMessage(event) {
       if (event.action === "answerToActionA") {
         doSomethingResolveCallback(event.data);
       }
    }