jQuery/JavaScript: accessing contents of an iframe

jQuery/JavaScript: accessing contents of an iframe

I would like to manipulate the HTML inside an iframe using jQuery.
I thought I’d be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:
$(function(){ //document ready
$(‘some selector’, frames[‘nameOfMyIframe’].document).doStuff()

However this doesn’t seem to work. A bit of inspection shows me that the variables in frames[‘nameOfMyIframe’] are undefined unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get permission denied-type errors).
Does anyone know of a work-around to this?


Solution 1:

I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.

Solution 2:

If the <iframe> is from the same domain, the elements are easily accessible as



Solution 3:

        $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');

Solution 4:

If the iframe src is from another domain you can still do it. You need to read the external page into PHP and echo it from your domain. Like this:


    $URL = "http://external.com"

    $domain = file_get_contents($URL)

    echo $domain

Then something like this:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>


    cleanit = setInterval ( "cleaning()", 500 );

function cleaning(){
    if($('#frametest').contents().find('.selector').html() == "somthing"){
        $('#selector').contents().find('.Link').html('ideate tech');


<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>

The above is an example of how to edit an external page through an iframe without the access denied etc…

Solution 5:



instead of


Solution 6:

I find this way cleaner:

var $iframe = $("#iframeID").contents();