0

I'm trying

$(document).ready(function(){   
    var myIFrame = document.getElementById("myIframe");
        var content = myIFrame.contentWindow.document.body.innerHTML;
    alert(
        content
    );
})

but I get an access denied error I guess because what I have loaded in the frame is Google. Is what I want to do even possible? The document must be an external one (like Google). And I would like to loop through all elements in the document. I'm a newbie on JS and JQuery so I might be missing a very basic thing.

Juan
  • 15,274
  • 23
  • 105
  • 187
  • possible duplicate of [jquery/javascript: accessing contents of an iframe](http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe) – Felix Kling Sep 01 '10 at 20:27

3 Answers3

4

You can't because of the Same Origin Policy, implemented in all common browsers.
The protocol, host, domain and port of two IFRAME pages must match(having the same origin) to allow javascript to communicate between them.

If you want to enable cross domain communication in javascript you need some cooperation from the other domain.

Now if you plan to read something less ambitious than google.com, and the other domain is ready to communicate with you, here are two techniques:

  1. For modern browsers you can use parent.postMessage from the IFRAME and have a listener in the main page to receive a string message.
     
  2. For older browsers you can use tricks like passing string data i.e. through windows.name or the window.location.hash
    But with those tricks you will have to poll with a setInterval to check for changes.
Mic
  • 24,812
  • 9
  • 57
  • 70
2

No, this is called cross site scripting (XSS), and is disabled for security.

livingtech
  • 3,570
  • 29
  • 42
1

Try doing this:

$(document).ready(function(){
    iframe = $('#myIframe');
    alert($(iframe).contents());
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337