Cross-Domain Communication: Parent window and child iframe
This respository provides you with the example code to enable cross-domain communication between a parent window and child iframe. To learn more about how to use the code and how to enable cross-domain communication (for this specific case), view my Medium article below:
The article shows you how to enable cross-domain communication by allowing a child iframe to send data to its parent window. It does not show you how to perform communication from the parent window to the child iframe. If you're interested in performing parent-to-child communication, then read the section below.
Sending data from the parent window to the child iframe
The parent window can send its child iframes messages. It takes the same code as child-to-parent communication, but differs in three ways:
- The code is reversed
targetWindow.postMessage()call is called from the parent window
targetWindow.postMessage()call is the child iframe's window object. For example,
parent.postMessage()is used in child-to-parent communication and (assuming the use of jQuery)
$("iframe").contentWindow.postMessage()is used in parent-to-child communication.
$("iframe").contentWindowis the iframe's window object.
Note: The example code below assumes you're using jQuery.
In the parent window, add the function that sends a message to the child iframe:
In the child iframe, add the logic that handles messages sent from other windows:
Open up your project in the browser and type the following in the console:
sendMessageToChild("Hello, child iframe!");
Note: You might see
undefinedpop up in the console. That doesn't mean the code is broken. That's going to happen because
sendMessageToChild()doesn't return anything.