【问题标题】:JavaScript cross domain access from subdomain in iframe来自 iframe 中子域的 JavaScript 跨域访问
【发布时间】:2015-03-27 05:17:19
【问题描述】:

父页面位于 site.com。我的页面位于 sub.site.com 上,该页面将通过 iframe 包含在父页面中。根据https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy,这应该可以通过让 sub.site.com 页面将其域更新为 site.com 来实现。但是,当我尝试此操作时,由于相同的来源策略,我仍然会收到拒绝访问错误。

site.com:

<html>
<head></head>
<body><iframe src="http://sub.site.com"/></body>
</html>

sub.site.com:

<html>
<head>
<script>
    function setupPage() {
    try {
        var oldDomain="current iframe domain: ";
        oldDomain = oldDomain.concat(document.domain);
        alert(oldDomain);

        document.domain='sakai.rutgers.edu';
        var newDomain="new iframe domain: ";
        newDomain = newDomain.concat(document.domain);
        alert(newDomain);

        var parentDomain="parent domain: ";
        parentDomain = parentDomain.concat(parent.window.document.domain);
        alert(parentDomain);

    }
    catch (err) {
        var e = "Caught error: ";
        e = e.concat(err.message);
        alert(e);
    }
</script>
</head>
<body onload=setupPage()>
<p>Test Page</p>
</body>

当我加载父页面时,前两个警报显示域正在按预期重置。但是,当脚本尝试访问 parent.window.document.domain 时,会抛出以下错误(在 Chrome 中): “捕获的错误:阻止具有源“http://sub.site.com”的框架访问跨域框架。”

我错过了什么?

【问题讨论】:

    标签: javascript cross-domain


    【解决方案1】:

    我认为在你可能想要使用的代码中

    parentDomain = parentDomain.concat(document.domain); 
    

    而不是

    parentDomain = parentDomain.concat(parent.window.document.domain);
    

    在第一种情况下,我猜它对当前窗口可用,因此它将获取文本并将其连接起来。如果您需要访问父窗口,请使用

    parent.window.frames.documents............ 
    

    希望有所帮助。我自己不是大师,但我以前遇到过这些情况,而这种技术已经解决了问题。

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 2011-08-28
      • 2010-10-16
      • 1970-01-01
      • 2011-12-09
      相关资源
      最近更新 更多