Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - HTML5 - Cross Browser iframe postMessage - child to parent?

I've been following this tutorial - http://www.youtube.com/watch?v=R2hOvZ7bwXU, which explains how to use postMessage to securely pass a message between iframe and parent - you basically end up with something like this - http://html5demos.com/postmessage2

My problem is that I need it to work the opposite way round (child to parent) and don't know how to target the parent window.

this is my receiver code (in the parent):

function handleMsg(e) {
    if(e.origin == "http://uc.dialogue.net") {
        let blah = e.data;
        alert(blah);    
    } else {
        alert("error");
    }
}
addEventListener("message", handleMsg, true);

and this is the sender function that is triggered by a simple form (in child):

   let text = document.querySelector('.srchInput').value;
   window.parent.postMessage(text, "http://uc.dialogue.net");   

Should I be targeting the parent in a different way?

Cheers Paul

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
    var key = e.message ? "message" : "data";
    var data = e[key];
    //run function//
},false);

Got it to work with the above in the parent page and the following in the child page - ???

parent.postMessage("loadMyOrders","*");  //  `*` on any domain         

Code copied from here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...