Cross-origin Communication between Parent Page and iframe Child Page

Author: įŽĄį†å‘˜ Published at: Jul, 2 2025 Hits: 9

When the parent page and the iframe child page are cross-origin, directly calling functions will cause cross-origin errors. You need to use postMessage to pass messages.


Parent Page Calling Child Page

Parent page code:

 
var frame = document.getElementById("frame-id"); frame.contentWindow.postMessage({ name: "abc", age: 18 }, "*");

postMessage takes two parameters:

  • The first parameter is any data type, usually an object that encapsulates business data.

  • The second parameter is the target origin. By default, it is "/", but using "*" allows cross-origin calls.


iframe Child Page Code

 
window.addEventListener("message", function(event) { console.log(event); // event.data is the message object sent from the parent page // event.data.name is the 'name' property sent from the parent page // event.data.age is the 'age' property sent from the parent page });

You can get the passed data via event.data.


Child Page Calling Parent Page

iframe child page code:

js
 
window.parent.postMessage({ name: "abc", age: 18 }, "*");

The parameters are defined the same way as the parent page calling the iframe child page.


Parent Page Code to Receive Messages from Child Page

 

 
window.addEventListener("message", function(event) { console.log(event); // event.data is the message object sent from the child page // event.data.name is the 'name' property sent from the child page // event.data.age is the 'age' property sent from the child page });

💡 If you enjoy my content and find it helpful,
feel free to support me — every donation means a lot!

User Comments
å¯ŧčˆĒ