Home > Web Front-end > JS Tutorial > How do you use postMessage in javascript?

How do you use postMessage in javascript?

藏色散人
Release: 2021-09-12 16:44:06
forward
3460 people have browsed it

The parent page and the child page are in different domains, and postMessage is used in the dialogue between them. Below for convenience, they are collectively referred to as pages F and C.

The click event of the button on page C sends a message small C to page F. When page F receives the message small C executes the logic LC. After the LC execution is completed, page F sends a message small F to page C. Page C receives the message. To message small F execute logical LF. In a word, it means that pages F and C communicate with each other.

Can be thought of as

similar to parent-child component communication in react.

C page js code:

var btnObj = document.getElementById('buttons');
btnObj.onclick = function(){
     var defaultAdData = {
                 type:'advert', 
                 gameData:{
                     adId: '123'
                 }
         };
     window.parent.postMessage(JSON.stringify(defaultAdData), '*');
    /*我是错误代码:
     var receiveMessage = function(event) {
         var datas = JSON.parse(event.data);
         if (datas.type === "adGivePrize"&&datas.givePrize) {
             alert(‘click’);
         }
     }
     window.addEventListener("message", receiveMessage, false);*/
 }
 /*我是正确代码:
 var receiveMessage = function(event) {
     var datas = JSON.parse(event.data);
     if (datas.type === "adGivePrize"&&datas.givePrize) {
         alert(‘click’);
     }
 }
 window.addEventListener("message", receiveMessage, false);*/
Copy after login

F page js code:

var receiveMessage = function(event) {
      var datas = JSON.parse(event.data);
      if (datas.type === "advert") {
            var postIframeData = {
                    type:'adGivePrize',
                    givePrize:true
            };
            //iframe发送信息~~~~
            window.frames[0].postMessage(JSON.stringify(postIframeData), '*');
      }
}

window.addEventListener("message", receiveMessage, false);
Copy after login

In short, this method provides communication between two unrelated pages, allowing external projects or Embedded iframes can communicate with each other.

Recommended study: "javascript basic tutorial"

The above is the detailed content of How do you use postMessage in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template