How To Post Message Between Iframe / Popup Window And Parent Window Example

This article will tell you how to use the javascript window object’s postMessage(message, targetOrigin) method to post text messages ( or javascript object’s JSON string data ) between the iframe/popup window and it’s parent window with examples.

1. How To Post Message Between Html Window & iFrame/Popup Window Steps.

  1. Call the window object’s addEventListener(“message”, function(event){…}, false); method to register the message event to the window object, then when a message is sent to the window object, it can process the message in the registered function, below is an example.
    window.addEventListener("message", function(event){
    
        var evOrigin = event.origin;
        var messageData = event.data; 
        console.log(evOrigin);
        if(evOrigin == 'http://localhost:8080'){
            alert('Receive the message "' + messageData + '" from ' + evOrigin);
        }else{
            alert('The message event original source is ' + evOrigin);
        }
    }, false);
  2. Call the window object’s postMessage(message, targetOrigin) method to post the message to the target iframe or popup window. The message parameter is the data to send, the targetOrigin parameter is the target URI (contains protocol://domain:port_number) of the iframe or popup window.
  3. The message will only send to the window that the URI matches the targetOrigin. You can also use * to send the message to any target iframe or popup window.

2. Post Message Between iFrame/Popup Window And Parent Window Example.

  1. There are 5 files in this example, they are index-1.html, frame1.html, frame2.html, frame3.html, and CustomHttpWebServer.py.
    $ tree ./
    ./
    ├── CustomHttpWebServer.py
    ├── frame1.html
    ├── frame2.html
    ├── frame3.html
    └── index-1.html
    
  2. The python file CustomHttpWebServer.py is the python file that will start an HTTP web server, and then we can access the 4 Html files to see the example.
  3. First, start the HTTP web server by executing the CustomHttpWebServer.py python file, you can also use your own HTTP webserver to run the example.
  4. Then copy the other Html files into the HTTP web server root folder.
  5. Browse the URL http://localhost:8080/ in your web browser, then it will list all the example files.
  6. Click the file index-1.html to open the main Html page, there are 2 iframes and 2 links below the iframes.
  7. The first iframe will receive & display the message posted from the parent window, it will also post the message back to the parent window.
  8. The second iframe will not receive the message posted from the parent window, because the post message target origin is not correct, it lost the http:// protocol.
  9. When you click the red text Open frame3.html in a popup window., it will open a new tab window to display the frame3.html.
  10. When you click the red text Post message between the popup window & this window., it will post the messages between the popup window and the current browser window.
  11. index-1.html.
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Post message from iframe to parent window example.</title>
        <script type="text/javascript">
    
            /* Register the message event process listener function to process the message sent from other page window object ( iframe, popup window, etc). */
            window.addEventListener("message", function(event){
                // Get the message event emitter origin URI.
                var evOrigin = event.origin;
                // Get the message data.
                var messageData = event.data; 
                console.log(evOrigin);
                // If the message event sent from the URI http://localhost:8080.
                if(evOrigin == 'http://localhost:8080'){
                    alert(messageData + '" from ' + evOrigin);
                }else{
                    alert('The message event original source is ' + evOrigin);
                }
            }, false);
    
          
            // Post text message to the first iframe.
            function postMessage1(){
                // Get the frist iframe window object.
                var iframe1 = window.frames[0];
                // Post the message to the iframe window, the target origin is correct.
                iframe1.postMessage('Hello to iframe1 from parent window', 'http://localhost:8080');
    
            }
    
            // Post text message to the second iframe.
            function postMessage2(){
    
                var iframe2 = window.frames[1];
                // The target origin is not correct which lost the http protocol, then iframe2 will not receive the posted message.
                iframe2.postMessage('Hello to iframe2 from parent window', 'localhost:8080');
            }
    
            var popupWindow = null;
            // Open a popup window to show the frame3.html.
            function openPopupWindow(){
                if(popupWindow == null){
                    popupWindow = window.open("frame3.html", 'popup');
                }
            }
    
    
            // Post text data to the opened popup window.
            function postMessageToPopupWindow(){
                if(popupWindow != null){
                    // post the message to the popup window of any URI ( represented by * ).
                    popupWindow.postMessage('Hello to popup window from parent window', '*');
                }
            }
        </script>
    </head>
    <body>
    <h1>Post message between iframe and parent window example.</h1>
    <h3>iFrame1</h3>
    <iframe width="600" src="frame1.html" onload="postMessage1()">
    </iframe>
    
    <h3>iFrame2</h3>
    <iframe width="600" src="frame2.html" onload="postMessage2()">
    </iframe>
    
    <h3>Post message between popup window.</h3>
    <a onclick="openPopupWindow()" style="display: block;color:red">Open frame3.html in a popup window.</a>
    <a onclick="postMessageToPopupWindow()" style="display: block;color:red">Post message between popup window & this window.</a>
    </body>
    </html>
  12. frame1.html.
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <script type="text/javascript">
    
            // listen on the message sent from the parent window.
            window.addEventListener("message", function(event){
    
                var evOrigin = event.origin;
                var messageData = event.data; 
                
                var parentMessage = "Receive message \"" + messageData + "\" sent from parent window, parent window URL is " + evOrigin; 
    
                document.body.innerHTML = parentMessage;
    
                // send message from frame1 to the parent window.
                event.source.postMessage('iframe1 has received the message sent from parent window, parent window URL is ' + event.origin, event.origin);
    
            }, false);
    
        </script>
    </head>
    <body>
    </body>
    </html>
  13. frame2.html.
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <script type="text/javascript">
    
            window.addEventListener("message", function(event){
    
                var evOrigin = event.origin;
                var messageData = event.data; 
                
                var parentMessage = "Receive message \"" + messageData + "\" sent from parent window, parent window URL is " + evOrigin; 
    
                document.body.innerHTML = parentMessage;
    
                // send message from frame1 to the parent window.
                event.source.postMessage('iframe2 has received the message sent from parent window, parent window URL is ' + event.origin, event.origin);
    
            }, false);
    
        </script>
    </head>
    <body>
    </body>
    </html>
  14. frame3.html.
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <script type="text/javascript">
            
            // Listen to the message event and process it. 
            window.addEventListener("message", function(event){
    
                var evOrigin = event.origin;
                var messageData = event.data; 
                
                var parentMessage = "Receive message \"" + messageData + "\" sent from parent window, parent window URL is " + evOrigin; 
    
                alert(parentMessage);
                
                document.body.innerHTML = parentMessage;
    
                // send message from the popup window to the parent window.
                event.source.postMessage('Popup window has received the message sent from parent window, parent window URL is ' + event.origin, event.origin);
    
            }, false);
    
        </script>
    </head>
    <body>
    </body>
    </html>
  15. CustomHttpWebServer.py: run this python file to start an HTTP web server, you can see the command in section 16.
    import http.server
    from http.server import HTTPServer, BaseHTTPRequestHandler
    import socketserver
    
    PORT = 8080
    
    Handler = http.server.SimpleHTTPRequestHandler
    
    Handler.extensions_map={
        '.manifest': 'text/cache-manifest',
        '.html': 'text/html',
        '.png': 'image/png',
        '.jpg': 'image/jpg',
        '.svg':	'image/svg+xml',
        '.css':	'text/css',
        '.js':	'application/x-javascript',
        '': 'application/octet-stream', # Default
        }
    
    httpd = socketserver.TCPServer(("", PORT), Handler)
    
    print("the web server is listening on port", PORT)
    httpd.serve_forever()
  16. Open a terminal and CD into the above python file saved directory, then run the command python ./CustomHttpWebServer.py to start the webserver.
    $ ls -l
    total 40
    -rw-r--r--  1 songzhao  staff   553 Apr 30 21:42 CustomHttpWebServer.py
    -rw-r--r--  1 songzhao  staff   780 Apr 30 21:42 frame1.html
    -rw-r--r--  1 songzhao  staff   718 Apr 30 21:42 frame2.html
    -rw-r--r--  1 songzhao  staff   844 Apr 30 22:29 frame3.html
    -rw-r--r--  1 songzhao  staff  2708 Apr 30 23:11 index-1.html
    (base) songs-MacBook-Pro:post-message songzhao$ 
    (base) songs-MacBook-Pro:post-message songzhao$ 
    (base) songs-MacBook-Pro:post-message songzhao$ python ./CustomHttpWebServer.py 
    the web server is listening on port 8080
    127.0.0.1 - - [30/Apr/2022 23:24:58] "GET / HTTP/1.1" 200 -

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky