Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
Edi Avatar asked Apr 29 '14 11:04

Edi


People also ask

How do I get around the same origin problem with iframe?

A webpage inside an iframe/frame is not allowed to modify or access the DOM of its parent or top page and vice-versa if both pages don't belong to same origin. A frame or child page can bypass this restriction by setting window. document. domain variable to the same domain name as the parent's domain name.

How do I fix not allowed by Access-Control allow origin?

There Are Two Approaches to Getting It Right.Use a reverse proxy server or WSGI server(such as Nginx or Apache) to proxy requests to your resource and handle the OPTIONS method in the proxy. Add support for handling the OPTIONS method in the resource's code.

Is iframe cross-origin?

iframe Security 101All Browsers implement a Cross-Origin Access Restriction to prevent the host document from accessing the iframe document, unless they have the same origin. This is done to prevent embedded documents access to your sites cookies, localStorage data etc.


1 Answers

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.

like image 175
Alexey Ten Avatar answered Sep 26 '22 00:09

Alexey Ten