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 use JavaScript to implement sorting algorithms

Table of contents Bubble Sort Selection Sort Inse...

Table related arrangement and Javascript operation table, tr, td

Table property settings that work well: Copy code ...

MySQL 5.7.18 Archive compressed version installation tutorial

This article shares the specific method of instal...

Customization Method of Linux Peripheral File System

Preface Generally speaking, when we talk about Li...

Let's talk about the storage engine in MySQL

Basics In a relational database, each data table ...

Vue implements simple calculator function

This article example shares the specific code of ...

VM VirtualBox virtual machine mount shared folder

One environment Install VMware Tools on CentOS 7 ...

How to use MySQL DATEDIFF function to get the time interval between two dates

describe Returns the time interval between two da...

Detailed steps to install mysql5.7.18 on Mac

1. Tools We need two tools now: MySQL server (mys...

Solve the problem that Docker must use sudo operations

The steps are as follows 1. Create a docker group...

Pure CSS to achieve the effect of picture blinds display example

First, let me show you the finished effect Main i...

Implementation of Docker CPU Limit

1. --cpu=<value> 1) Specify how much availa...

Detailed explanation of the use of shared memory in nginx

In the nginx process model, tasks such as traffic...

What is COLLATE in MYSQL?

Preface Execute the show create table <tablena...