3

I have an html page (test.html) on my computer (localhost). In an iframe on that page I have abc.example.com loaded.

I want to access the contents of the iframe abc.example.com from another domain xyz.example.com. Here is what I've tried so far:

//test.html in abc.example.com
<input type="textbox" />
<input type="submit" value="click_me" />

//Start.html in xyz.example.com

<script type="text/javascript">
  $(document).ready(function() {

    $("#ok").click(function() {
      //using javascript
      var oo = document.getElementById("myFrame");

      document.getElementById("divFrame").innerHTML = 
        oo.contentWindow.document.body.innerHTML;   
    });

  });
</script>

<iframe id="myFrame" src="http://localhost/exam/test.html"></iframe>
<div id="divFrame"></div>
<input type="submit" id="ok" />

But when I press the "ok" button, it throws an "Access is Denied" error. I also get the same error when using jQuery to simulate clicks in the iframe:

var btn = window.frames[0].document.getElementsByName('click_me');
btn[0].click();
Jay
  • 18,959
  • 11
  • 53
  • 72
  • 5
    its a different domain name it won't work. [Same origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) – Ibu Aug 20 '12 at 18:10
  • 1
    Related: http://stackoverflow.com/questions/1088544/javascript-get-element-from-within-an-iframe and http://stackoverflow.com/questions/11053910/how-do-i-get-this-child-html-element-in-javascript/11054105#11054105. The answers to both of these questions indirectly address your problem, which is that you cannot access the contents of a cross-domain iframe. – apsillers Aug 20 '12 at 18:18

1 Answers1

4

In JavaScript you don't have access to frames on a different domain. It's called the Same origin Policy. If this was allowed you could, for instance, open a hidden frame to load facebook and google+ and steal everyone's info!

In some cases there is a way around the same origin policy but you need to explicitly whitelist a domain. Like when using Cross-origin resource sharing. So it is possible to dynamically (AJAX/XMLHTTPRequest) fetch data from another domain, but you must control the other domain as well.

Halcyon
  • 57,230
  • 10
  • 89
  • 128