Origin不适用于同一域中的iframe

Origin不适用于同一域中的iframe

本文介绍了Access-Control-Allow-Origin不适用于同一域中的iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问子域中的iframe并收到跨域错误.

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

I'm trying to access an iframe within a subdomain and get a cross domain error.

Here is the code of 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的代码:



And here is the code of 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()行时,发生以下错误:



When the line $('#innerdiv',$('iframe').contents()).hide() is executed, the following error occurs:

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的内容?


I checked with Fiddler that the Access-Control-Allow-Origin header was really returned in the response of welcome.php

Is it possible to access the contents of an iframe within a subdomain?

推荐答案

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

您所需要的称为相同起源政策.

您必须在页面中添加 document.domain ='example.com'.

这篇关于Access-Control-Allow-Origin不适用于同一域中的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:05