Can Cross-Origin Resource Sharing headers authorize X-Domain IFRAME access?
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 开发者_StackOverflow社区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?
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)
精彩评论