Web & React: <iframe>

When using an iframe to display embedded experiences, you need to provide a communication channel so the embedded experience can send messages to your app.

Use the MessageChannel API to create a channel. Its two ports are connected to either end: you keep port1 and listen on it, and you send port2 into the iframe, where the embedded experience uses it to send events to your app.

Attach a load listener to the iframe before you set its src, so the listener is in place when the embedded experience finishes loading. In the listener, create the channel, start listening on port1, and send port2 to the iframe:

const iframe = document.createElement("iframe");

iframe.addEventListener("load", () => {
  const channel = new MessageChannel();

  channel.port1.onmessage = (event) => {
    // event.data.eventHandlerName is the name you provided when creating the session;
    // event.data.eventType identifies the event
  };

  iframe.contentWindow.postMessage("", "*", [channel.port2]);
});

iframe.src = embeddedSessionUrl;
document.getElementById("everee-container").appendChild(iframe);

Pass port2 in the transfer list, the third argument to postMessage. A port passed any other way, for example inside the message data, does not reach the embedded experience.

Creating the channel inside the load listener gives every page load its own pair of ports. A port can only be transferred once, so if the iframe reloads, it needs a new channel.

React

In React, attach the listener with an onLoad prop. React registers it before the iframe starts loading:

function EvereeEmbed({ url, onEvereeEvent }) {
  const handleLoad = (event) => {
    const channel = new MessageChannel();
    channel.port1.onmessage = (message) => onEvereeEvent(message.data);
    event.currentTarget.contentWindow.postMessage("", "*", [channel.port2]);
  };

  return <iframe src={url} onLoad={handleLoad} title="Everee" />;
}

Confirm the connection

The first event you receive on port1 is MESSAGE_PORT_REGISTERED. If it never arrives, the embedded experience shows error EMB-102. To find out why, open your browser's developer console on the page that hosts the iframe and look for lines starting with [everee.embedded]. The EMB-102 line begins with the reason the connection failed. You can also run window.evereeEmbeddedDiagnostics.getReport() in the iframe's console context and send us the output.

The event's data property will be a JavaScript object. See Component Events for details of the data structure.


Did this page help you?