【问题标题】:Cross-origin access with jQuery: accessing frames in subdomain in Internet Explorer fails使用 jQuery 进行跨域访问:在 Internet Explorer 中访问子域中的帧失败
【发布时间】: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


    【解决方案1】:

    发生错误是因为在第二种情况下,设置框架的 document.domain 的脚本是在框架的加载事件触发后执行的。将代码放在 frame.ready() 中并没有帮助 - 在脚本执行之前框架就准备好了。在所有浏览器中都会发生这种情况,但由于某种原因只会在 IE 中导致错误。

    因此,当前的解决方案实际上是一种 hack - 框架准备好后 100 毫秒超时,以便框架内的脚本在访问框架之前执行。

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 1970-01-01
      • 2013-11-04
      • 2014-03-05
      • 2014-03-15
      • 2012-02-12
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      相关资源
      最近更新 更多