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.


