我试图访问子域名中的一个iframe,但是出现了跨域错误。
这是example.mydomain.com/iframe_test.html的代码:
这是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 内容?
Uncaught SecurityError: Failed to set the 'domain' property on 'Document': 'example.com' is not a suffix of ''.
。 - Mike R