Learn how to communicate between two web pages of different origin

In some of our projects, we have a requirement to load an Iframe inside a website and pass data between them.

If the parent window and the Iframe window belongs to the same domain, then the communication between them works seamlessly.

If both belong to the different domain, Say the parent belongs to https://domain1.com and the iframe belongs to https://domain2.com, then data transfer between the window and iframe using JavaScript is difficult because it is against the same origin policy of browser.

Same Origin Policy quotes as follows :

A Web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin

Two web pages are said to be the same origin then it must have the same protocol, same domain name, and same port.

How to pass data between cross-domain pages?

Communication between two web pages of different origin is possible with the help of Window.postMessage() method. Let us see how to use post message to send data.

Consider a web page of origin https://domain1.com loads an iframe of origin https://domain2.com.

Now the parent window domain1.com needs to send data to the iframe domain2.com Then write the following code in domain1.com to send the data using the window.PostMessage() Method

Part 1: The Sender domain1.com

Create an iframe of source https://domain2.com

<iframe id="my-iframe" src="https://domain2.com" ></iframe>
<input type="button" value="Send Message" onClick="sendMsgToIframe();"/>

Then inside the sendMsgToIframe() method, send a message to the iframe as below:

function sendMsgToIframe(){
var iframeWindow = document.getElementById("my-frame").contentWindow;
iframeWindow.postMessage("Hello world", "https://domain2.com");

In the above script, the message “Hello world” is being sent to the iframe window using the postMessage() method.

Part 2: The Receiver (domain2.com)

Now we are going to write a message event handler function in the iframe to receive the message.

window.addEventListener('message', function(event){
if(event.origin === "https://domain1.com"){
alert("Data Received :"+event.data);

When the iframe window receives the message from domain1.com, it will alert as “Data Received: Hello world”.

Always validate the origin using event.origin to check the data is received from a trusted website to avoid any security breach.

This is how we can send a message between two cross-domain pages.

The above process can be followed to send a message back from iframe to parent window, between a parent and child pop-up window.