【发布时间】: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" 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 确认 Access-Control-Allow-Origin 标头确实在welcome.php 的响应中返回
是否可以访问子域内 iframe 的内容?
【问题讨论】:
标签: javascript iframe cross-domain-policy