Categories
iframe javascript jquery same-origin-policy

How can I access the contents of an iframe with JavaScript/jQuery?

837

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?

5

  • 3

    What does the iFrame contain – is its src set to another domain?

    – James

    Dec 14, 2008 at 0:32

  • if it is a other domain,is there still a way to access its content or register an event

    Oct 1, 2009 at 15:59

  • 37

    No, because that would be cross-site scripting, which is prohibited for security reasons. My solution was to use a proxy: feed the HTML in the IFRAME verbatim through my own site so it’s no longer cross-site fro mthe browser’s perspective.

    Apr 6, 2010 at 8:10

  • 1

    It’s more cross-browser to use .contentWindow.document than .document on the iframe element. I’ll suggest the change above.

    – Alan H.

    Jul 8, 2011 at 20:04

  • 1

    one way is chrome extensions

    Apr 16, 2013 at 13:14

402

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.

1

  • 10

    @Tracker1: Can you suggest any framework/api/design pattern for implementing this proxy solution. Any links to example or tutorial etc? I have tried to search but couldn’t find any.

    Jun 27, 2012 at 12:26

402

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.

1

  • 10

    @Tracker1: Can you suggest any framework/api/design pattern for implementing this proxy solution. Any links to example or tutorial etc? I have tried to search but couldn’t find any.

    Jun 27, 2012 at 12:26

97

You could use .contents() method of jQuery.

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

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

0