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

How do you use postMessage in javascript?

藏色散人
藏色散人forward
2021-09-12 16:44:063391browse

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);*/

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);

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete