This section provides the technical information required to use JavaScript to
communicate between a HTML document referenced via iFrame and the parent HTML
document enclosing iFrame.
Lets consider a HTML document enclosing an iFrame like this:
<BODY id="parentBody"
onClick="showParentInfo();">
<P id="parentP">Hello, this is a parent frame</P> <INPUT id="parentCode" type="hidden" value="Hello from Parent"/> <DIV id="parentDisplay"></DIV> <IFRAME id="childFrame" src="childFrame.html" scrolling="yes" frameborder="0" height="400" width="400"> <p>Your browser does not support iframes.</p> <IFRAME> </BODY>
with a JS function:
function showParentInfo()
{
var iFrame = window.parent.document.getElementById("childFrame"); var iFrameDocument = iFrame.contentDocument? iFrame.contentDocument: iFrame.contentWindow.document; iFrameDocument.getElementById('childDisplay').innerHTML = this.document.getElementById("parentCode").value;
}
And the iFrame content can be something like this: <DIV id="childBody" onClick="showchildinfo();"> <P>Hello, this is a child frame</P> <INPUT id="childCode" value= "Hello from Child"/> <DIV id="childDisplay"></DIV> </DIV> with a JS function: function showchildinfo() { var document = window.parent.document; document.getElementById('parentDisplay').innerHTML = this.document.getElementById("childCode").value; } Parent to Child Window Communication: To access the DOM elements/Javascript fucntions of the HTML document referenced from iFrame, we need to get the below references: 1. Reference to the iFrame Element var iFrame = window.parent.document.getElementById("childFrame"); 2. Reference to the Document object of the source referenced by the iFrame var iFrameDocument = iFrame.contentDocument? iFrame.contentDocument: iFrame.contentWindow.document; Once we have the DOM Element reference, any element type can be accessed and manipulated. For example, here we are pushing a hidden input's value from parent document to the HTML document's DIV Element referenced from iFrame: iFrameDocument.getElementById('childDisplay').innerHTML = this.document.getElementById("parentCode").value; And the JavaScript fucntion can be accessed in a similar way: iFrameDocument.showchildinfo(); Child to Parent Window Communication: To access the DOM elements/Javascript fucntions of the HTML document enclosing the iFrame, the parent window's document object has to be retrieved: var document = window.parent.document; Once we have the DOM object, DOM elements/JavaScript fucntions can be accessed: DOM Element: document.getElementById('parentDisplay').innerHTML = this.document.getElementById("childCode").value; Javascript Fucntion: window.parent.document.showparentinfo(); |
Thursday, November 8, 2012
Communication with an iFrame
Labels:
Web App Development
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment