iframe中的脚本可以与主页中的脚本交互

问题描述:

我有一个带有SWF多图像上传器的编辑器。由于不是每个人都需要在他们的文章中上传图片,我需要在必要时动态加载此图片上传器。我必须将其加载到iframe中,因为上传者需要一些外部脚本才能加载。因为我需要它的回调变量为我的编辑器使用我想知道iframe中的脚本是否可以与主页中的脚本进行交互。或者如果我不能这样做,有什么替代方法来做到这一点?iframe中的脚本可以与主页中的脚本交互

如果他们在同一个域上,是的。

parent对象是iframe的父窗口。

如果您在父窗口的在全球范围内有一个变量a,你可以操纵它在iframe这样的:

parent.a = "new value"; 

同样,如果a是在父的全球范围内的函数窗口中,你可以这样调用它:

parent.a(args); 

能在IFRAME脚本的主要页面的脚本互动

仅当iframe及其父母具有完全相同的域时,由于same origin policyMDC link)。

Html5中的postMessage支持Internet Explorer 8.0+,Firefox 3.0+,Safari 4.0+,Chrome 1.0+和Opera 9.5+,这是我一直在使用它的方式。如果你不介意IE7和更早版本缺乏支持,下面介绍如何实现它。

的Javascript在主窗口:

window.addEventListener("message", receiveMessage, false); 

function receiveMessage(event){ 
    var source = event.source.frameElement; //this is the iframe that sent the message 
    var message = event.data; //this is the message 
    //do something with message 
} 

的Javascript在iframe;

var message='hello, big window!'; //could be of any type, string, number, array, object, have fun 
window.parent.postMessage(message,'*'); //the '*' has to do with cross-domain messaging. leave it like it is for same-domain messaging. 

当然,你可以做到这一点倒过来,让主窗口发送消息的iframe,并有一定的交叉窗口对话的方式。

如果iframe来自不同的域,但您可以控制内容,则可以通过两种不同的方式在两者之间进行通信。最简单的方法是通过iFrame的URL中的键/值对“交谈”,因为父级和iFrame都可以访问该对象。

一个更复杂的方法是使用iFrame代理,这在这里描述得非常好:http://www.julienlecomte.net/blog/2007/11/31/它使用雅虎管道来回发送消息很好。

为了延长安迪的回答Can scripts in iframe interact with scripts in the main page

使用jQuery.postMessage插件http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html

浏览器上测试的Internet Explorer 6-8,Firefox 3中,Safari浏览器3-4,Chrome浏览器,Opera 9中