Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
rz. Avatar asked Dec 13 '08 07:12

rz.


People also ask

How do I access elements in an iframe?

Getting the element in Iframeconst iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.

How can get iframe HTML using jQuery?

# jQuery Code to Get HTML Content of IFrame$("#myButton"). on('click', function() { alert($("#myIframe"). contents(). find("html").


2 Answers

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

$("#iFrame").contents().find("#someDiv").removeClass("hidden"); 

Reference

like image 70
Yasir Laghari Avatar answered Sep 20 '22 22:09

Yasir Laghari


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.

like image 25
Onur Bebin Avatar answered Sep 20 '22 22:09

Onur Bebin