Ability to send messages between power-up iframes

Hi!

It would be good to have an ability communicate throught postMessage between power-up iframes in order to share a data. Main power-up iframe connector and card-back iframe could be share data, users list as example.
Let me know if it make sense.

I have had to do this. I created this class in JavaScript:

/**
 * Class to help pass messages between forms
 */
export default class MessageHook {
  /** @type {Hook[]} */
  #hooks = [];
  /**
   * CONSTRUCTOR - starts the loop 
   */
  constructor() {
    // main loop
    window.setInterval(()=>{
      /** @type {String} */
      const value = window.sessionStorage.getItem("callbackMessage");
      if(value) {
        const data = JSON.parse(value);
        var hookToRemove = -1;
        for(var i=0;i<this.#hooks.length;i++) {
          if(data.from === this.#hooks[i].listenFor) {
            window.sessionStorage.removeItem("callbackMessage"); // processed
            // call the callback
            this.#hooks[i].callback(data.value, data.asyncValues);
            hookToRemove = i;
            break;
          }
        }
        if(hookToRemove >= 0) {
            this.#hooks = this.#hooks.splice(hookToRemove, 1);
        }
      }
    }, 200); // 5 per second
  }
  /**
   * Adds a hook to the Message handler
   * @param {*} callback 
   * @param {*} from 
   * @param {*} asyncValues
   */
  addMessageHook = (callback, listenFor, asyncValues) => {
    this.#hooks.push({
      listenFor: listenFor,
      callback: callback,
      asyncValues: asyncValues,
    });
  }
  /**
   * Sends a message to any attached message Hook
   * @param {*} msg 
   * @param {*} from 
   */
  sendMessage(value, from) {
    window.sessionStorage.setItem("callbackMessage", JSON.stringify({ from: from, value: value }));
  }
}
/**
 * @typedef {Object} Hook
 * @property {String} listenFor
 * @property {MessageHookCallback} callback
 * @property {Object} asyncValues
 */
/** 
 * @callback MessageHookCallback
 * @param {Object} value
 * @param {Object} asyncValues
 */

I then declare this in a common location to my app:

static AppMessageHook = new MessageHook();

Then I use it like this:

AppMessageHook.addMessageHook(async (value)=>{ 
  // this is what happens when I receive a message
  // for -vvvv- this caller name.
}, "callerName");

// now here you open up your frame
t.popup(...);

Next, in the caller iframe, I do this when I want to go back to the code callback above:

AppMessageHook.sendMessage(value, "callerName");

This allows for multiple message hooks across multiple frames and automatically cleans up once it recieves the message.

Let me know if this help.

1 Like