Introduction
Sometimes, we need to achieve the following inside Parent Page.
- Get the values of controls inside
iFrame
- Set value to Child controls inside
iFrame
Background
This was a piece of research, which came up while I was writing the Blog Skype Status on CRM Form.
If possible, please go through the Blog.
What is the Concept?
Normally, we would do something like the following to get the Control
inside the Document
.
var yourChildiFrameControl = document.getElementById("childiFrameControlId");
But when we write this code inside Parent Page, Document
will refer to the Parent Page and not the iFrame
. This will give you undefined JavaScript error
as the Control
is not present inside Parent Document.
So, the aim is to find the Document
Object of iFrame
first and with the help of that object, find any Control
inside it.
How To Do This?
Before getting the Document
Object of iFrame
, let's trap the iFrame
first.
var childiFrame = document.getElementById("iFrameID");
Now, with the help of the trapped iFrame
object (childiFrame
), let's retrieve the iFrame Document
.
var innerDoc = childiFrame.contentDocument
|| childiFrame.contentWindow.document;
Note: Here the OR
statement is used for the Cross Browser Support. As contentDocument
does not work in IE, so contentWindow.document
is used. To know more, refer to Frame/IFrame contentDocument Property.
So, we got the iFrame Document
(innerDoc
). Now it is just a matter of searching the Control by Id inside this Document
.
var yourChildiFrameControl = innerDoc.getElementById("childiFrameControlId");
Thus, we can easily Get or Set value using the Control
object (yourChildiFrameControl
).
var value = yourChildiFrameControl.value;
yourChildiFrameControl.value = "Your value";
Note: As we obtained the Control
object (yourChildiFrameControl
) which is inside the iFrame
, we can do all JavaScript DOM operations on that.
Important Note
This technique will work, if the Parent Page and iFrame
both are in the Same Domain.
If any of them is in a Different Domain, then we have to follow Window Message Passing technique, which I have described in my tip - Communication with Cross Domain IFrame - A Cross Browser Solution.
Did You Like It?
If you find this tip helpful, then please vote it up, share and add some comments. It really means a lot. That will also help me to fine tune my technical skills. Thanks for reading. Hope you enjoyed the tip.
Points of Interest
The interesting part of the Tip/Trick is, we just found the Document
of iFrame
and that's it. Boom!!!
History
- 25 September, 2013: Initial post
- 26 September, 2013: Added "Important Note" Section