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

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

问题描述

调整IFRAME的高度以匹配其内容页的高度可以是一个真正的拖动



跨源资源共享(CORS)标头使内容页面成为可能授权跨域访问其资源,从而允许其包含的页面读取其高度? (或者,包含页面授权内容页面宣布它的高度?)



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


< divs =h2_lin>解决方案

CORS不允许这样做,但是您可以使用跨文档消息传递在iframes及其父窗口之间发送字符串,即使在不同的域上,并使用



大多数浏览器都支持此功能,但 Internet Explorer的方式不同



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

  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是针对其他人的。



EDIT 跨文档邮件的浏览器支持(-fsb)


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?

解决方案

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)

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

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