Access-Control-Allow-Origin not working for iframe withing the same domain

Edi*_*Edi 10 javascript iframe cross-domain-policy

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>
Run Code Online (Sandbox Code Playgroud)



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>
Run Code Online (Sandbox Code Playgroud)



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. 
Run Code Online (Sandbox Code Playgroud)


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?

Ale*_*Ten 18

Access-Control-Allow-Origin is used only for XHR.

What you need is called Same Origin Policy.

You have to add document.domain = 'example.com' to your pages.

  • 这不起作用,我得到:`Uncaught SecurityError:无法在'Document'上设置'domain'属性:'example.com'不是''的后缀. (10认同)
  • 该解决方案已被弃用 (3认同)
  • 我们应该在哪里添加 document.domain 的东西?能不能再详细一点。谢谢你。 (2认同)
  • 关于弃用的说明:https://developer.mozilla.org/en-US/docs/Web/API/Document/domain (2认同)