Can Cross-Origin Resource Sharing headers authorize X-Domain IFRAME access?

CORS doesn’t let you do that, but you can use cross-document messaging to send strings between iframes and their parent windows even on different domains, and use that to communicate.

Most browsers support this although Internet Explorer’s way differs from the others‘.

Assuming what you want is to have the iframe announce to the parent page its desired height, you could put this in your iframe code (not tested):

var message = {
    width: desiredWidth,
    height: desiredHeight
};
window.parent.postMessage(JSON.stringify(message),'*');

And this in your containing page:

function onMessage (event) {
    if (event.source != theIFrameElement.contentWindow) return;
    var message = JSON.parse(event.data);
    var desiredHeight = message.height;
    var desiredWidth = message.width;   
}

if (window.attachEvent)
    window.attachEvent('onmessage', onMessage);
else if (window.addEventListener)
    window.addEventListener('message', onMessage, false);

The attachEvent is for IE and addEventListener is for everyone else. You might want to check the target origin for security purposes, but that’s the general idea.

EDIT: Browser support for Cross-document messaging (—fsb)

Leave a Comment