同域名下的iframe中Access-Control-Allow-Origin无法工作

17
我试图访问子域名中的一个iframe,但是出现了跨域错误。

这是example.mydomain.com/iframe_test.html的代码:

<html>
<head>
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
    <iframe src="http://example2.mydomain.com/welcome.php" width="1000" height="600"></iframe>
    <script>
        $(document).ready(function()
        {
            setTimeout(function(){
                $('#innerdiv',$('iframe').contents()).hide();
            },5000);
        });
    </script>
</body>
</html>



这是example2.mydomain.com/welcome.php的代码:

<?php
header("Access-Control-Allow-Origin: " . "*");
?>
<html>
<head>

</head>
<body>
    <div id="innerdiv">
        hello
    </div>
</body>
</html>


在执行代码行 $('#innerdiv',$('iframe').contents()).hide() 时,会出现以下错误:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://example.mydomain.com" from accessing a frame with origin "http://example2.mydomain.com". Protocols, domains, and ports must match. 


我用 Fiddler 工具检查了 welcome.php 响应头部返回的 Access-Control-Allow-Origin 头信息。

在子域名中是否可以访问 iframe 内容?

2个回答

25

Access-Control-Allow-Origin仅用于XHR。

你需要的是称为同源策略

你需要在你的页面中添加document.domain = 'example.com'


2
我们应该在哪里添加那个 document.domain 的东西?您能详细解释一下吗?谢谢。 - Saeed Neamati
13
无法正常运行,我得到了以下错误提示:Uncaught SecurityError: Failed to set the 'domain' property on 'Document': 'example.com' is not a suffix of ''. - Mike R
@MikeR,你的文档地址是什么? - Alexey Ten
3
此解决方案已被弃用。 - skini82
2
关于弃用的说明:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/domain - quadratecode
显示剩余3条评论

-2
我在使用Divi主题的WordPress网站中的custom.unified.js文件中找到了关于"Access-Control-Allow-Origin"的解决方案,并通过添加以下条件进行了修正。
        if (window.parent != window.top) {
    window.top && window.top.__Cypress__ ? r = window.parent === window.top ? window : window.parent : window.top && (r = window.top, window.top, window.self)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接