Secure communication between LWC and iFrame using window.postMessage()

Telegram logo Join our Telegram Channel
Secure communication between LWC and iFrame using window.postMessage()


Hello Friends, Data Virtualization is a great way to use third-party apps inside Salesforce to save space and reuse the code. 

This third-party app can be your own website or third-party SaaS tool, you can easily embed that in Salesforce. One of the ways to implement data virtualization is to use a third party site as an iFrame in Salesforce.

In this article, we will see how to establish secure two-way communication between the Lightning web component and any web page embedded in iFrame.


Hypothetical Example

Let us create a Visualforce page and embed it in LWC to demonstrate this with an example. Although we use a Visualforce page here, any webpage can achieve this communication.

Let us create two buttons, one in LWC and another on the Visualforce page. Both buttons will fire the window.postMessage() event from its parent to the intended receiver.


The window.postMessage() function

The window.postMessage facilitates secure communication between different windows on a webpage. It allows scripts in separate windows (parent/child, iframes, popups) to exchange data without compromising security.

There are three parameters to this function:

  • message (required):
    The data you want to send to the target window. This can be a string, a number, an object (often JSON-formatted for complex data), or any other data type that can be serialized using the structured clone algorithm.
  • targetOrigin (optional):
    A string specifying the origin (domain) of the target window you want to send the message to.
    If omitted, the message is sent to all frames whose origin matches the current window's origin.
    Use "*" to allow any origin (less secure, use with caution!).
  • transfer (optional):
    An optional array of Transferable objects (like ArrayBuffer or MessagePort) that you want to transfer ownership of to the target window. This can improve performance when dealing with large data sets.

Note: the message and targetOrigin parameters that we are using mostly.

As we already know the postMessage function provides one-way communication, we need to implement the event handlers a both ends. So let us understand both directions one by one.


LWC To iframe

Fire Event from LWC to iframe (Visualforce page)

To communicate with iframe windows within your LWC component, you can leverage the window.postMessage function. This allows you to securely exchange data between the LWC component and the content displayed within the iframe.

myComponent.html

<iframe src="https://forcetrails-dev-ed--c.vf.force.com/apex/postMessaageVf"></iframe>

myComponent,js

    this.template.querySelector("iframe").contentWindow.postMessage("message to send", "*");

While the above example uses "*" as the target origin for simplicity, it's crucial to specify the actual origin of the page embedded within the iframe. Using "*" allows messages from any origin, which can be a security risk.  Always restrict the target origin to the expected source of the iframe content to prevent unauthorized message reception.


Handle event in an iframe (Visualforce page)

This code snippet demonstrates the usage of window.postMessage in JavaScript. While the example is within a Visualforce page, this functionality applies to any web application that supports JavaScript, regardless of the specific front-end framework used.


myVisualforce.page

window.addEventListener(
  "message",
  (event) => {
    console.log("📃 VF:in vf event handler");
    //  change the origin according to you
    if (event.origin !== LIGHTNING_ORIGIN) return;

    alert("📃 VF: Message from LWC: " + JSON.stringify(event.data))
  },
  false,
);


IFrame to LWC

While receiving messages from the LWC component on the Visualforce page was simpler, establishing communication in the opposite direction (iframe to LWC) requires more steps.


Fire event from iframe to LWC

myVisualforc.page

window.parent.postMessage("message to lwc", "*");

The above code snippet utilizes window.parent.  Since iframes are embedded within a parent window, this approach allows the iframe to communicate with its surrounding window (the LWC component in this case).


Handle event in LWC

  // Connect message handler when component is loaded
  connectedCallback() {
    window.addEventListener("message", (event) => {
      // verify origin
      if (event.origin !== "https://forcetrails-dev-ed--c.vf.force.com") {
        console.log("data", event.data);
      }
    }, false);
}

This code defines an event handler function. Whenever the LWC component receives a message from the embedded iframe, the code within this function will be executed. This allows the LWC component to react to events or data transmitted from the iframe.

While receiving messages from the LWC on the Visualforce page is relatively straightforward, communication in the opposite direction (iframe to LWC) requires more effort. This is because iframes need to proactively listen for messages or events.


Output




Full Working Code Example

For a complete understanding and implementation details, refer to the full working code sample available in a public Git repository lwc-iframe-commucation

I hope this blog post empowers you to implement secure communication between LWCs and iframes in your Lightning Web Components applications!


No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com