9

Adjusting the height of an IFRAME to match its content page's height can be a real drag when the containing and content pages are not from the same domain.

Do the Cross-Origin Resource Sharing (CORS) headers make it possible for the content page to authorize cross-domain access to its resources and thus allow its containing page to read its height? (or, alternatively, the containing page authorize the content page to announce its height?)

Or is CORS strictly an AJAX thing?

Community
  • 1
  • 1

1 Answers1

17

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)

PaulG
  • 186
  • 1
  • 3
  • Browsers that support `onmessage` are modern ones? IE8, FF3 etc? –  Jun 23 '11 at 23:18
  • 2
    Here is a browser support table. I could only add 2 links to my answer because I didn't have enough rep for more. http://caniuse.com/x-doc-messaging – PaulG Jun 24 '11 at 00:03
  • 1
    thanks for the browser support table link and the answer. I’m accepting it on the assumption that you’re right that CORS doesn’t help but especially for going beyond the original question with a very useful alternative. `onmessage` is worth knowing about. –  Jun 24 '11 at 14:01
  • Let's see if I can add your browser support table to your answer. –  Jun 24 '11 at 14:02