Access-Control-Allow-Origin 不适用于同一域中的 iframe
Posted
技术标签:
【中文标题】Access-Control-Allow-Origin 不适用于同一域中的 iframe【英文标题】:Access-Control-Allow-Origin not working for iframe within the same domain 【发布时间】:2014-06-15 06:48:22 【问题描述】:我正在尝试访问子域中的 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" ></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 确认 Access-Control-Allow-Origin 标头确实在welcome.php 的响应中返回 是否可以访问子域内 iframe 的内容?
【问题讨论】:
【参考方案1】:Access-Control-Allow-Origin
仅用于 XHR。
你需要的是Same Origin Policy。
您必须将document.domain = 'example.com'
添加到您的页面。
【讨论】:
我们应该在哪里添加 document.domain 的东西?你能详细说明一下吗。谢谢。 @SaeedNamati 您需要将它添加到两个页面的脚本标记中。基本上主页面和iframe页面需要设置<script>document.domain = 'example.com'</script>
这不起作用,我得到:Uncaught SecurityError: Failed to set the 'domain' property on 'Document': 'example.com' is not a suffix of ''.
@MikeR 你的文件地址是什么?
此解决方案已弃用【参考方案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)
【讨论】:
以上是关于Access-Control-Allow-Origin 不适用于同一域中的 iframe的主要内容,如果未能解决你的问题,请参考以下文章