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

69,802

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.

Share:
69,802
Edi
Author by

Edi

Updated on August 03, 2022

Comments

  • Edi
    Edi almost 2 years

    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>
    



    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>
    



    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. 
    


    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?

  • Saeed Neamati
    Saeed Neamati over 9 years
    Where should we add that document.domain stuff? Can you elaborate a little more. Thank you.
  • Maksim Luzik
    Maksim Luzik over 9 years
    @SaeedNeamati You need to add it to both of the pages into script tag. Basically the main page and the iframe page need to have <script>document.domain = 'example.com'</script> set
  • Mike R
    Mike R about 9 years
    This doesn't work, I get: Uncaught SecurityError: Failed to set the 'domain' property on 'Document': 'example.com' is not a suffix of ''.
  • Alexey Ten
    Alexey Ten about 9 years
    @MikeR what address of your document?
  • Sayuj3
    Sayuj3 over 7 years
    <script>document.domain = 'example.com'</script> where to paste is exactly.? I pasted it but didnt wrk properly.
  • tarn
    tarn about 7 years
    Must use document.domain = 'localhost'; or your domain You should open in web server, not a local file
  • skini82
    skini82 almost 3 years
    This solution is deprecated
  • quadratecode
    quadratecode over 2 years