Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access iframe elements in JavaScript

I have a webpage where there is a textarea within an iframe. I need to read the value of this textarea from its child page using JavaScript.

Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.

Can anyone please give me any pointers to resolve this issue?

like image 952
archana roy Avatar asked Sep 20 '09 14:09

archana roy


People also ask

Can javascript access iframe content?

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.

Can we access Dom in iframe?

The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.

How do I check if an element is an iframe?

In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.


1 Answers

If your iframe is in the same domain as your parent page you can access the elements using window.frames collection.

// replace myIFrame with your iFrame id // replace myIFrameElemId with your iFrame's element id // you can work on window.frames['myIFrame'].document like you are working on // normal document object in JS window.frames['myIFrame'].document.getElementById('myIFrameElemId') 

If your iframe is not in the same domain the browser should prevent such access for security reasons.

like image 124
RaYell Avatar answered Oct 14 '22 19:10

RaYell