Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

javascript - cross site iframe postMessage from child to parent

I found this samplefrom SO while browsing for my problem, but I want to know exactly how to use it in my scenario. I have an iframe which is from another domain, and I want to detect when the iframe url is changed from one to another page in that other domain. So, what I was thinking is to have something like this when the 2nd page in the iframe is opened:

<script type="text/javascript">
    $(document).ready(function() {
parent.postMessage("Second Page");
}
</script>

That's all I need, I just need to receive message that the iframe has different url. Now on the parent page, I'll might have something like this:

<script type="text/javascript">
    $(document).ready(function() {
        $('#frame').load(function () { 
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
 var secondPageValue = // I want to get the value from the child page here, how can I do that?
},false);               
        });
    });
</script>

I'm trying to use this postMessage option for first time, so every advice will be greatly appreciated. Also, do I need to include some JS libraries such as jquery on child side to make this work?

Thanks in advance, Laziale

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to set targetOrigin when using postMessage.

<script type="text/javascript">
    $(document).ready(function() {
       parent.postMessage("Second Page",'*');
    }
</script>

Then on the host page.

function addAnEventListener(obj,evt,func){
    if ('addEventListener' in obj){
        obj.addEventListener(evt,func, false);
    } else if ('attachEvent' in obj){//IE
        obj.attachEvent('on'+evt,func);
    }
}

function iFrameListener(event){
     secondPageValue = event.data;
}

var secondPageValue='';

addAnEventListener(window,'message',iFrameListener);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...