Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

In the actual development, we may encounter the page of project B nested in project A, or some portal websites. When the site contains some other projects, we can also adopt this way to communicate with each other by passing tokens and other information between different domain names.

API,

Two processes were set up to simulate the communication

The parent interface address is: http://192.168.169.1/test

Son of the interface address is: http://192.168.169.1:81/test1

The parent boundary passes information to the child interface:

The parent interface:

<h1> Home page </h1><p class="title" @click="handleANew">Send a message</p>
      <iframe id="child" src="http://192.168.169.1:81/test1" style="width: 100%; height: 800px"></iframe>
      <div>
        <h2>The main area receives messages</h2>
        <! -- <span id="message"></span> -->
      </div>

	handleANew() { 
      document
        .getElementById("child")
        .contentWindow.postMessage("hhhhh"."http://192.168.169.1:81/test1");
    },
Copy the code

The child interface:

<h2> subpage </h2><div>
      <h3>Receiving message area</h3>
      <span id="message"></span>
    </div>
    
	<script>
	window.addEventListener(
	  "message".function (event) {
	    console.log(event);
	    document.getElementById("message").innerHTML =
	      "Receive" + event.origin + "News:" + event.data;
	  },
	  false
	);
	</script>
Copy the code

After clicking Send message:

The message can then be delivered to the child page

The child passes information to the parent interface:

The child interface:

<script>
    window.addEventListener('message'.function(event){
        console.log(event);
        document.getElementById('message').innerHTML = "Receive" 
            + event.origin + "News:" + event.data;
        top.postMessage("Child page message received".'http://192.168.169.1/test')},false);
</script>
Copy the code

The parent interface:

window.addEventListener('message'.function(event){
    document.getElementById('message').innerHTML = "Receive" 
        + event.origin + "News:" + event.data;
}, false);
Copy the code

tip:

1. Distinction between postMessage and sendMessage (synchronization);

2. When using Webpack, Webpack itself will send postMessage. Pay attention to distinguish whether message is sent by itself or webpackOK when listening for message.

Cross-domain communication using Iframe + postMessage (see link)