跨域资源共享标头可以授权 X-Domain IFRAME 访问吗? [英] Can Cross-Origin Resource Sharing headers authorize X-Domain IFRAME access?

查看:19
本文介绍了跨域资源共享标头可以授权 X-Domain IFRAME 访问吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调整 IFRAME 的高度以匹配其内容页面的高度 可能是一个真正的阻力 当包含页面和内容页面来自不同的域时.

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.

跨域资源共享 (CORS) 标头是否可以让内容页面授权跨域访问其资源,从而允许其包含页面读取其高度?(或者,包含页面授权内容页面宣布其高度?)

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?)

还是严格来说 CORS 是 AJAX 的东西?

Or is CORS strictly an AJAX thing?

推荐答案

CORS 不允许您这样做,但是您可以使用跨文档消息传递在 iframe 与其父窗口之间甚至在不同域上发送字符串,并使用沟通.

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.

虽然Internet Explorer 的方式有所不同,但大多数浏览器都支持这一点来自其他'.

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

假设您想要的是让 iframe 向父页面宣布其所需的高度,您可以将其放入 iframe 代码中(未测试):

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),'*');

这在你的包含页面中:

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);

attachEvent 适用于 IE,而 addEventListener 适用于其他所有人.出于安全目的,您可能想要检查目标来源,但这是一般的想法.

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.

编辑:浏览器支持跨文档消息传递 (—fsb)

这篇关于跨域资源共享标头可以授权 X-Domain IFRAME 访问吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆