Javascript Html5 - 跨浏览器 Iframe postmessage - 子级到父级?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8822907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:40:22  来源:igfitidea点击:

Html5 - Cross Browser Iframe postmessage - child to parent?

javascriptjqueryhtmljquery-mobile

提问by Dancer

I've been following this tutorial - http://www.youtube.com/watch?v=R2hOvZ7bwXU, which basically 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

我一直在关注本教程 - http://www.youtube.com/watch?v=R2hOvZ7bwXU,它基本上解释了如何使用 postmessage 在 iframe 和父级之间安全地传递消息 - 你基本上最终会得到这样的东西 - http://html5demos.com/postmessage2

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

我的问题是我需要它以相反的方式工作(子到父)并且不知道如何定位父窗口。

this is my receiver code (in the parent) -

这是我的接收器代码(在父级中)-

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

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

这是由一个简单的表单(在子表单中)触发的发送器函数 -

   var text=$('.srchInput').val();
   window.parent.postMessage(text, "http://uc.dialogue.net");   

Should I be targeting the parent in a different way?

我应该以不同的方式定位父母吗?

Cheers Paul

干杯保罗

回答by Dancer

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.

这里复制的代码。

回答by Avindra Goolcharan

A modern, simplified version of the accepted answer (which drops legacy ie8 support in favor of terseness):

已接受答案的现代简化版本(放弃对传统 ie8 的支持以支持简洁):

window.addEventListener('message',function(e) {
    var key = e.message ? 'message' : 'data';
    var data = e[key];
    //run function//
},false);

Please see:

请参见: