Juan
Juan

Reputation: 15715

How can I access the contents of a frame or iframe with JavaScript or JQuery?

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.

Upvotes: 0

Views: 786

Answers (3)

Mic
Mic

Reputation: 25164

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.

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227240

Try doing this:

$(document).ready(function(){
    iframe = $('#myIframe');
    alert($(iframe).contents());
});

Upvotes: 1

livingtech
livingtech

Reputation: 3660

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

Upvotes: 2

Related Questions