Monday, June 4, 2012

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 unaccessible (I get permission denied type errors).

Does anyone know of way to work around this?

Source: Tips4all


  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.

  2. If the iframe is the same domain, the elements are easily accessible as



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

  4. You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

    $().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
    $('some selector', frames['nameOfMyIframe'].document).doStuff();

    The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

  5. 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 = ""

    $domain = file_get_contents($URL)

    echo $domain

    Then something like this:


    <script type="text/javascript" src=""></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="" ></iframe>

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

  6. use
    iframe.contentWindow.document instead of iframe.contentDocument

  7. Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?

    $(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
    } );