在所有浏览器中传递来自iFrame的消息 [英] Passing Messages from iFrame Across all Browsers

查看:189
本文介绍了在所有浏览器中传递来自iFrame的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



换句话说,iframe需要通过单击按钮时向其父级发送消息。



在涉及不,跨域策略是一个混蛋的海洋中,我找到了< a href =https://developer.mozilla.org/en/DOM/window.postMessage> window.postMessage ,HTML5草案规范的一部分。



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

  window.addEventListener('消息',goToThing,false); 

函数goToThing(event){
//检查原点,以确保它来自可信来源。
if(event.origin!=='http:// localhost')
return;

// event.data应该是id,一个数字。
//如果是,则使用该ID进入页面。
if(!isNaN(event.data))
window.location.href ='http:// localhost / somepage /'+ event.data;
}

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



$ $ $ $'$ c $ $ $''''。submit(function(){
parent.postMessage(someId,'*') );
});

真棒,对不对?唯一的问题是它似乎不适用于任何版本的IE。所以,我的问题是这样的:鉴于我需要从传递一个iframe给它的父母(两者都是我控制的)的消息,是否有我可以使用的方法任何(> IE6)浏览器?

解决方案

在父窗口中检测值并检测父项中的散列值,解析散列值以获取数据并执行任何您想要的操作。以下是一个例子: http://www.onlineaspect.com / 2010/01/15 /向后兼容,PostMessage的/ 。 Google有更多选项可供选择: http://easyxdm.net/wp/


I have an embed-able iframe that will be used on 3rd party sites. It has several forms to fill out, and at the end must inform the parent page that it is done.

In other words, the iframe needs to pass a message to it's parent when a button is clicked.

After wading through oceans of "No, cross-domain policy is a jerk" stuff, I found window.postMessage, part of the HTML5 Draft Specification.

Basically, you place the following JavaScript in your page to capture a message from the 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;
}

Then in the iframe, have some JavaScript that sends a message to the parent:

$('form').submit(function(){
    parent.postMessage(someId, '*');
});

Awesome, right? Only problem is it doesn't seem to work in any version of IE. So, my question is this: Given that I need to pass a message from an iframe to it's parent (both of which I control), is there a method I can use that will work across any (>IE6) browser?

解决方案

The main work-around I've seen used involves setting a hash value on the parent window and detecting the hash value in the parent, parsing the hash value to obtain the data and do whatever you want. Here's one example of doing that: http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/. There are more options via Google like this one: http://easyxdm.net/wp/.

这篇关于在所有浏览器中传递来自iFrame的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆