Can scripts in iframe interact with scripts in the main page

前端 未结 5 2009
遥遥无期
遥遥无期 2021-01-13 06:03

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 nece

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 06:54

    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.

提交回复
热议问题