【发布时间】:2013-02-27 10:27:12
【问题描述】:
如果加载时文档中已经存在带有来自子域的源的iframe标签,IE9可以访问,但如果在文档中插入相同的iframe,IE9无法访问(其他所有浏览器都可以)。请参阅下面的代码 sn-ps。
这是正常的 IE9 行为还是可以通过某种方式修复? Google 这次没有提供帮助,因此非常感谢您的帮助。
这适用于 Internet Explorer 9 和所有其他浏览器
example.com 中的主文档:
<div class="container">
<iframe src="sub.example.com/index.html"></iframe>
</div>
<script>
document.domain = 'example.com';
var frame = $('iframe', 'container')
, el = frame.contents().find('div.hello'); // usually returns 1 element
if (el.length > 0)
el.html('Hello'); // sets div content in iframe
else // sometimes it gets here, if script runs before iframe loads
frame.on('load', function(){
el = frame.contents().find('div.hello'); // works if the 1st one fails
el.html('Hello');
});
</script>
子域中的文档(sub.example.com/index.html):
<script>document.domain = 'example.com'</script>
<div class="hello"></div>
这适用于所有浏览器,但不适用于 IE9(错误:访问被拒绝)
example.com 中的主文档:
<div class="container"></div>
<script>
$('div.container').html('<iframe src="sub.example.com/index.html"></iframe>');
document.domain = 'example.com';
var frame = $('iframe', 'container')
, el = frame.contents().find('div.hello'); // throws error
// ...
</script>
子域中的文档是一样的。
在实际代码中,.container 的内容是由模板函数生成的,因此使用 .html() 将其作为简单文本插入,就像示例中一样。
感谢任何帮助使第二个案例在 IE 中工作。
【问题讨论】:
标签: jquery internet-explorer iframe cross-domain