2009
Jun
17
Communicate Between iFrames
iFrame Attributes
Example
- <iframe id="my-iframe" height="100%" width="100%" src="child.html" allowtransparency="true" frameborder="0" scrolling="No"></iframe>
The self
and top
properties give an easy way to check if the page is inside a frame.
Example
- if (window.self !== window.top) {
- console.log("Inside a frame.");
- }
Access iFrames
Access Child
- // Get child element.
- window.frames["iframeName"].document.getElementById(id);
- // Get child variable.
- window.frames["iframeName"].propertyName;
- // Run child function.
- window.frames["iframeName"].functionName();
Access Parent
- // Get parent element.
- parent.document.getElementById(id);
- // Get parent variable.
- parent.propertyName;
- // Run parent function.
- parent.functionName();
Trigger window.onload
To make sure that any elements that may effect the content's height are loaded, I normally attach the function to the window.onload
event.
Example
- window.onload = function (e) {
- var iframeElement = document.getElementById("my-iframe"),
- size = getSize(iframe);
- iframeElement.style.height = size.height + "px";
- iframeElement.style.width = size.width + "px";
- };
Get iFrame Size
The document containing the iframe can obtain references to properties and elements in the iframed document through contentDocument
or contentWindow
properties. The contentDocument property has broad support among current browsers, including Internet Explorer 8+, Firefox, Chrome, Safari and Opera. The contentWindow property is supported by Internet Explorer 5.5+, Firefox, Chrome, Safari and Opera.
Example
- function getSize(iframe) {
- var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document,
- body,
- html,
- height = 0,
- width = 0;
- // from http://stackoverflow.com/questions/1145850/get-height-of-entire-document-with-javascript
- doc = doc || document;
- body = doc.body;
- html = doc.documentElement;
- height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
- width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
- console.log("body.scrollHeight = " + body.scrollHeight + ", body.offsetHeight = " + body.offsetHeight);
- console.log("html.clientHeight = " + html.clientHeight + ", html.scrollHeight = " + html.scrollHeight + ", html.offsetHeight = " + html.offsetHeight);
- return {height: height, width: width};
- }
回應 (Leave a comment)