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
166 views
in Technique[技术] by (71.8m points)

javascript - Passing Messages from iFrame Across all Browsers

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In IE you should use

attachEvent("onmessage", postMessageListener, false);

instead of

addEventListener("message", postMessageListener, false);

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

...