Passing Messages from iFrame Across all Browsers

2019-01-22 04:57发布

问题:

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?

回答1:

The main work-around I've seen used involves setting a hash value on the parent window and detecting the hash value in the parent, parsing the hash value to obtain the data and do whatever you want. Here's one example of doing that: http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/. There are more options via Google like this one: http://easyxdm.net/wp/.



回答2:

In IE you should use

attachEvent("onmessage", postMessageListener, false);

instead of

addEventListener("message", postMessageListener, false);


回答3:

This is way simpler than that.

You say you control both the parent and the content of the frame you can set up two way communication in javascript.

All you need is

yourframename.document.getElementById('idofsomethinginttheframe')

And then from inside the frame address anything outside it with

parent.document