在所有浏览器中传递来自iFrame的消息

Dus*_*sda 12 javascript embed iframe html5

我有一个可嵌入的iframe,将在第三方网站上使用.它有几种形式可以填写,最后必须告知父页面它已完成.

换句话说,iframe需要在单击按钮时将消息传递给它的父级.

在浏览了"No,跨域策略是一个混蛋"的海洋之后,我找到了window.postMessage,它是HTML5草案规范的一部分.

基本上,您将以下JavaScript放在页面中以捕获来自iframe的消息:

window.addEventListener('message', goToThing, false);

function goToThing(event) {
    //check the origin, to make sure it comes from a trusted source.
    if(event.origin !== 'http://localhost')
        return;

    //the event.data should be the id, a number.
    //if it is, got to the page, using the id.
    if(!isNaN(event.data))
        window.location.href = 'http://localhost/somepage/' + event.data;
}
Run Code Online (Sandbox Code Playgroud)

然后在iframe中,有一些JavaScript向父母发送消息:

$('form').submit(function(){
    parent.postMessage(someId, '*');
});
Run Code Online (Sandbox Code Playgroud)

太棒了吧?唯一的问题是它似乎不适用于任何版本的IE.所以,我的问题是这样的:鉴于我需要将一条消息 iframe 传递给它的父节点(我控制它们),我可以使用哪种方法可以在任何(> IE6)浏览器中使用吗?

Kas*_*zaq 6

在IE中你应该使用

attachEvent("onmessage", postMessageListener, false);
Run Code Online (Sandbox Code Playgroud)

代替

addEventListener("message", postMessageListener, false);
Run Code Online (Sandbox Code Playgroud)


jfr*_*d00 3

我见过的主要解决方法包括在父窗口上设置哈希值并检测父窗口中的哈希值,解析哈希值以获取数据并执行您想要的任何操作。以下是这样做的一个示例:http://www.onlineaspect.com/2010/01/15/backwards-company-postmessage/。通过 Google 还有更多选项,例如:http: //easyxdm.net/wp/