🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

iframe-message-proxy

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

iframe-message-proxy

iframe-message-proxy

1.2.0
latest
npm
Version published
Weekly downloads
127
5.83%
Maintainers
1
Weekly downloads
 
Created
Source

Build Status

Iframe Message Proxy

This package is used for BLiP platform to handle communications between micro frontends, done by iframes throught postMessages. Basically, we send a message and wait for response. It is possible because every message sended to parent window throught IframeMessageProxy has a cached promise with an ID that is resolved when current window receive a message with the same ID. Jump to Usage section to more details.

Installation

npm i -S iframe-message-proxy

Usage

import { IframeMessageProxy } from 'iframe-message-proxy';

IframeMessageProxy.listen(); // Start listen for post messages

// Sending messages
IframeMessageProxy.sendMessage({
  action: 'customAction',
  content: 'Here is my awesome action',
});

sendMessage method takes an object as param that accept these properties:

PropertyTypeRequiredDescription
actionstringtrueAction sended to parent iframe. By default, is prefixed by blipEvent:
contentanyfalseActions can have optional contents added
fireAndForgetbooleanfalseMessages can have no response and be just a command to parent iframe
callerstringfalseEvery message has a caller. By default, is used child iframe name (passed as attribute on <iframe name="iframe-name">...) but you can set a custom caller name too.

By default, sendMessage method will send a postMessage to parent window and wait for some response, if has one.

// Child iframe
const action = await IframeMessageProxy.sendMessage({
  action: 'customAction',
  content: 'Here is my awesome action',
});

// Parent iframe
const iframe = document.getElementById('my-iframe').contentWindow; // Get iframe caller

// Handle received messages
const handleOnReceiveMessage = msgEvt: MessageEvent => {
  /**
   * Assuming that window can receive many postMessage events,
   * there is a tip to filter only messages camed from our library
   */
  const BLIP_EVENT_PREFIX = 'blipEvent:'
  const shouldHandleMessage = msg =>
    Object.keys(msg)
      .find(k => k == 'action' && msg.action.startsWith(BLIP_EVENT_PREFIX));

  if (!msgEvt.data || !message || !shouldHandleMessage(msgEvt.data.message)) {
    return;
  }

  /**
   * Every message has properties "message" and "trackingProperties".
   * "trackingProperties" is used by Iframe Message Proxy to identify
   * which promise will be resolved after send a postMessage, so
   * if you want to send something back to caller, you have to pass
   * trackingProperties received from child iframe.
   */
  const { message, trackingProperties } = msgEvt.data;

  iframe.postMessage({
    response: 'Success!',
    trackingProperties
  }, '*')
}

window.addEventListener('message', handleOnReceiveMessage);

Handling errors

If you want to send an error message to child iframe, you may also add error property to response object. In this way, the child iframe will reject the promise instead of resolve them.

try {
  doSomethingWrong();
} catch (e) {
  iframe.postMessage({
    error: e.toString(),
    trackingProperties
  }, '*')
}

Configuring

You can also configure defaults by config method:

IframeMessageProxy.config({
  prefix: 'customPrefix:',
  eventCaller: 'jarvis',
})

prefix?: string caller?: string receiveWindow?: Window targetWindow?: Window shouldHandleMessage?: ((message: IIdentifiedMessage) => boolean)

PropertyTypeDefaultDescription
prefixstringblipEvent:Action prefix
callerstringwindow.nameCaller name
receiveWindowWindowwindowWindow that will receive postMessages responses
targetWindowWindowwindow.parentWindow that we'll request something
shouldHandleMessage() => booleanundefinedYou can choose what message will be parsed or not by calling a function that takes a MessageEvent as argument. function(evt) { if (!evt.data) return false }

FAQs

Package last updated on 01 Sep 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts