Exchange data between HTML iframes

2

There is a special JavaScript messaging API which allows you to send messages between iframed windows and the main window of the web page.

Sending a message to a window (e.g. iframe) from another window (e.g. the main window of the currently opened page):

let iframe = document.getElementById("myframe");
iframe.contentWindow.postMessage("hello", "*");

To receive a cross-window message, recipient-side web page should subscribe to it:

window.addEventListener("message", function(event)
{
    if(event.data == "hello")
    {
        alert("The message is received!");
    }
}, false);

The sender window can be accessed via event.source property. You can reply to the sender like that:

window.addEventListener("message", function(event)
{
    if(event.data == "hello")
    {
        event.source.postMessage("good day!", "*");
    }
}, false);

In the example above I've sent and received a string message. However you can use this API to send and receive any kind of JavaScript objects in exactly the same way.

Share this page:

See also how to:

How to display beautiful math formulas on your website with MathJax JavaScript library
How to use WebSockets in web browser with JavaScript
How to use web browser local storage in JavaScript and what you should now about it
How to protect your website forms from unwanted spam bots
How to configure the web-server so you could make cross-domain AJAX-request to it