61

For say i have a Site called example.com on which iframe is embedded of domain iframe.net, now i want to read the content of iframe and pass some parameter to display a textual message. Like Hi with username.

Now the problem is this able not able to make connection between the two , even am not able to get the innerHTML of iframe i used following approach

document.getElementById('myframe').contentWindow.document.body.innerHTML;

It throws error "Permission denied to access property"

Do anyone know how to read and write in cross domain platform

Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59
  • You can use easyxdm library for communicating between cross domains. Here is a link please checkout. I had used this technique for resizing iframe(width, height) on cross domains. I am not sure whether this library works with your scenario. Give it a try. http://easyxdm.net/wp/ – Muhammad Sannan Khalid Feb 22 '12 at 11:44
  • 1
    Hi Muhammad, would you mind sharing how you achieved this? If you can remember - appreciate it was almost 7 years ago. – Sparlarva Jan 05 '19 at 16:15
  • it's possible but with some restrictions. You can check this https://alfilatov.com/posts/how-to-pass-data-between-iframe-and-parent-window/ – Alex Filatov Sep 30 '22 at 05:20

5 Answers5

80

If you don't have control over the framed site, you cannot circumvent the cross-domain policy.

If you have control over both sites, you can use the postMessage method to transfer data across different domains. A very basic example:

// framed.htm:
window.onmessage = function(event) {
    event.source.postMessage(document.body.innerHTML, event.origin);
};

// Main page:
window.onmessage = function(event) {
    alert(event.data);
};

// Trigger:
// <iframe id="myframe" src="framed.htm"></iframe>
document.getElementById('myframe').contentWindow.postMessage('','*');
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 2
    Is there any reverse cross domain proxy hacks to make it happen – Kunal Vashist Feb 22 '12 at 11:03
  • 1
    @KunalVashist Depends on your application (more details needed). Also have a look at this question [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy). – Rob W Feb 22 '12 at 11:10
  • Thx @rob this one is good , but eventually i don't have access to frame content – Kunal Vashist Feb 22 '12 at 11:25
  • if you are using jquery: `$(window).on('message', evt=>evt.originalEvent.data //...` – chiliNUT Apr 05 '17 at 23:34
  • 2
    https://stackoverflow.com/a/41566923/2969615 <-- similar answer with a bit more detail – Joe Coyle Jul 11 '18 at 13:51
  • yep. wrote about similar here https://alfilatov.com/posts/how-to-pass-data-between-iframe-and-parent-window/ – Alex Filatov Sep 30 '22 at 05:20
  • Apparently this doesn't work when the files originate on the local filesystem. You can access `event.data` but not `event.source`, which is confounding since I thought the point of postMessage was to enable scripted communication between different origins. But `event.source` prohibited by CORS policy, at least in Chrome. – Leslie Krause Dec 12 '22 at 15:45
7

In Internet Explorer 8, events passed as a parameter may be null, that is why you need to access the event in a different manner:

In frame.html:

window.onmessage = function(event) {
   var evt = event || window.event;
   evt.source.postMessage('Message from iFrame', evt.origin);
};

On main.html:

window.onmessage = function(event) {
   var evt = event || window.event;
   alert(evt.data);
};

The event is triggered the same way as Rob W has presented:

document.getElementById('frameId').contentWindow.postMessage('message','*');
Oladipo
  • 1,579
  • 3
  • 17
  • 33
Przemek Marcinkiewicz
  • 1,267
  • 1
  • 19
  • 32
0

It can happen only if you have control for both sites

you can use postMessage

here's how you can apply it

first, you can add the below code to the site you want to retrieve data from

 <script>
        function test() {       
 document.getElementById('idMyIframe').contentWindow.postMessage("your message here", "*");
        }
    </script>
    <iframe id="idMyIframe" onload="test()" src="http://example.otherdomaintosenddatato.com"></iframe>

the second step you can add this code below to the other domain you want to send a message or the data to it

 window.addEventListener("message", function (message) {
        if (message.origin == "http://firstdomain.com") {
            console.log(message)
        }
    });

and please note you must add the test() function on the onload attribute of the iframe cause if the function runs before the iframe was loaded it will become useless and it won't send data

Sandy Elkassar
  • 139
  • 1
  • 8
-1

Cross Domain iframe elements access in React with (srcDoc):-

<iframe srcDoc={this.state.HTML}  width='100%' id='iframetnd' onLoad={this.onclickinsideiframe}/>


 onclickinsideiframe=()=>{
      if(document.getElementById('iframetnd')!==null){

                let iframe = document.getElementById('iframetnd');

                let innerDocument = (iframe.contentDocument)  
                                   ? iframe.contentDocument 
                                   : iframe.contentWindow.document;
                let Obj = innerDocument.getElementsByClassName("navButtons")[0];
                    if(Obj !== undefined){
                        Obj.onclick = ()=>this.func();
          }
       }
    }



  func=()=>{
           this.setState({page:2})
           this.arrangeTest();
        }
P L DHIMAN
  • 59
  • 4
-2

iFrame does not allow to access contents from Cross Domain platform. You can only access if your iFrame is using the same domain.

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar.navbar-default\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}
Ahsan Horani
  • 239
  • 2
  • 13