开发者

Can scripts in iframe interact with scripts in the main page

I have an editor with an SWF multi-image uploader. Since not everyone will need to upload pictures in their article, i need to dynamically load this image uploader when necessary. I have to load it in an iframe because the uploader needs some external scripts to be loaded ahead. And since i need it's callback variable for my editor to use I want to know whether scripts in iframe can interac开发者_如何转开发ts with scripts in the main page. Or if i can't do that, what's the alternative way to do this?


If they are on the same domain, yes.

The parent object is the parent window of the iframe.

If you had a variable a in the global scope of the parent window, you could manipulate it in the iframe like this:

parent.a = "new value";

Similarly, if a is a function in the global scope of the parent window, you could call it like this:

parent.a(args);


postMessage in Html5, supported by Internet Explorer 8.0+, Firefox 3.0+, Safari 4.0+, Chrome 1.0+ and Opera 9.5+, is how I have been using it. If you don't mind the lack of support in IE7 and earlier versions, here's how to implement it.

Javascript in the main window:

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 in the 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.

Of course you could do it the other way round, having the main window sending messages to the iframe, and have some cross-window dialogue that way.


To extend Andy's answer Can scripts in iframe interact with scripts in the main page :

Use jQuery.postMessage plugin http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html

Browsers Tested Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 9.


Can scripts in iframe interact with scripts in the main page

Only if the iframe and its parent have the exact same domain, due to the same origin policy (MDC link).


If the iframe is from a different domain, but you have control over the content, you can communicate between the two in a couple different ways. The simplest is to "talk" through key/value pairs in the URL of the iFrame, since both the parent and the iFrame have access to that.

A more complicated approach is to use iFrame proxy's, which is described really well here: http://www.julienlecomte.net/blog/2007/11/31/ which uses Yahoo Pipes to send messages back and forth quite nicely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜