Example of implementing bidirectional messaging between parent and child pages in HTML iframe

Example of implementing bidirectional messaging between parent and child pages in HTML iframe

One day, the leader put forward a requirement to embed an iframe in the main page and send messages between the parent and child pages in both directions. Then I proposed a solution: postMessage

Knowledge theory preparation:

The postMessage method allows scripts from different sources to communicate asynchronously in a limited manner, and can achieve cross-text document, multi-window, and cross-domain message delivery.

grammar:

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow: A reference to another window, such as the contentWindow of an iframe, the window object returned by executing window.open, or named or numerically indexed window.frames.
  • message: data to be sent to other windows.
  • targetOrigin: Specifies which windows can receive message events. Its value can be the string "*" to indicate no restriction, or a URI.
  • transfer: is a string of Transferable objects that are passed along with the message. The ownership of these objects will be transferred to the recipient of the message, and the sender will no longer retain ownership.

When the postMessage method is called, a MessageEvent message is dispatched to the target window after all page scripts have been executed. The MessageEvent message has four properties that need to be noted:

  • type: indicates the type of the message
  • data: the first parameter of postMessage
  • origin: indicates the source of the window that calls the postMessage method
  • source: records the window object that calls the postMessage method

The operation process is as follows:

1. Prepare two pages

  • http://a.com/main.html Main page
  • http://b.com/iframepage.html Nested page

main.html

<!DOCTYPE html> 
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage cross-domain communication main page</title>
</head>
<body>
    <h1>Main Page</h1>
    <iframe id="child" src="http://b.com/iframepage.html"></iframe>
    <div>
        <h2>Main page receiving message area</h2>
        <span id="message"></span>
    </div>
</body> 
</html>

iframepage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage cross-domain communication subpage</title>
</head>
<body>
    <h2>Subpages</h2>
    <div>
        <h3>Receive message area</h3>
        <span id="message"></span>
    </div>
</body>
</html>

2. Parent sends message to child

main.html

<script>
    window.onload = function(){
        document.getElementById('child')
         .contentWindow.postMessage("Main page message", 
                "http://b.com/iframepage.html")
    }
</script>

Notice:

The message must be sent after the page is loaded, otherwise an error will be reported because the iframe has not been loaded.

Failed to execute 'postMessage' on 'DOMWindow'

Subpage receives message:

iframepage.html

<script>
    window.addEventListener('message',function(event){
        console.log(event);
        document.getElementById('message').innerHTML = "Received" 
            + event.origin + "Message: " + event.data;
    }, false);
</script>

At this point, you can see that the page is printed in the iframe's subpage.

Received message from http://a.com: Main page message`

And the console prints the MessageEvent object.

3. The child sends a message to the parent

The child page replies to the parent page after receiving the message

iframepage.html

<script>
    window.addEventListener('message',function(event){
        console.log(event);
        document.getElementById('message').innerHTML = "Received" 
            + event.origin + "Message: " + event.data;
        top.postMessage("Subpage message received", 'http://a.com/main.html')
    }, false);
</script>

The parent page receives the message and displays:

window.addEventListener('message', function(event){
    document.getElementById('message').innerHTML = "Received" 
        + event.origin + "Message: " + event.data;
}, false); 

4. Complete code

main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage cross-domain communication main page</title>
</head>
<body>
    <h1>Main Page</h1>
    <iframe id="child" src="http://b.com/iframepage.html"></iframe>
    <div>
        <h2>Main page receiving message area</h2>
        <span id="message"></span>
    </div>
</body> 
<script>
    window.onload = function(){
        document.getElementById('child')
         .contentWindow.postMessage("Main page message", 
            "http://b.com/iframepage.html")
    }
    window.addEventListener('message', function(event){
        document.getElementById('message').innerHTML = "Received"
         + event.origin + "Message: " + event.data;
    }, false);
</script>
</html>

iframepage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>iframe+postMessage cross-domain communication subpage</title>
</head>
<body>
    <h2>Subpages</h2>
    <div>
        <h3>Receive message area</h3>
        <span id="message"></span>
    </div>
</body>
<script>
    window.addEventListener('message',function(event){
        if(window.parent !== event.source){return}
        console.log(event);
        document.getElementById('message').innerHTML = "Received" 
            + event.origin + "Message: " + event.data;
        top.postMessage("Subpage message received", 'http://a.com/main.html')
    }, false);
</script>
</html>

This is the end of this article about the implementation example of html parent-child page iframe two-way messaging. For more relevant html parent-child page iframe two-way messaging content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

<<:  Introduction to using Unicode characters in web pages (&#,\u, etc.)

>>:  CSS achieves colorful and smart shadow effects

Recommend

How to connect to MySQL remotely through Navicat

Using Navicat directly to connect via IP will rep...

js code to realize multi-person chat room

This article example shares the specific code of ...

Understanding and application scenarios of enumeration types in TypeScript

Table of contents 1. What is 2. Use Numeric Enume...

The difference between shtml and html

Shtml and asp are similar. In files named shtml, s...

A question about border-radius value setting

Problem Record Today I was going to complete a sm...

Complete steps to build a Laravel development environment using Docker

Preface In this article, we will use Docker to bu...

Drop-down menu and sliding menu design examples

I found a lot of websites that use drop-down or sl...

Detailed explanation of MySQL date addition and subtraction functions

1. addtime() Add the specified number of seconds ...

WeChat applet implements a simple dice game

This article shares the specific code of the WeCh...

Pure CSS to achieve automatic rotation effect of carousel banner

Without further ado, let’s get straight to the co...

How to use webSocket to update real-time weather in Vue

Table of contents Preface About webSocket operati...

A brief introduction to Linux performance monitoring commands free

When the system encounters various IO bottlenecks...

Small problem with the spacing between label and input in Google Browser

Code first, then text Copy code The code is as fol...