2009
Jun
17

Communicate Between iFrames

iFrame Attributes

Example
  1. <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
  1. if (window.self !== window.top) {
  2. console.log("Inside a frame.");
  3. }

Access iFrames

Access Child
  1. // Get child element.
  2. window.frames["iframeName"].document.getElementById(id);
  3.  
  4. // Get child variable.
  5. window.frames["iframeName"].propertyName;
  6.  
  7. // Run child function.
  8. window.frames["iframeName"].functionName();
Access Parent
  1. // Get parent element.
  2. parent.document.getElementById(id);
  3.  
  4. // Get parent variable.
  5. parent.propertyName;
  6.  
  7. // Run parent function.
  8. 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
  1. window.onload = function (e) {
  2. var iframeElement = document.getElementById("my-iframe"),
  3. size = getSize(iframe);
  4. iframeElement.style.height = size.height + "px";
  5. iframeElement.style.width = size.width + "px";
  6. };

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
  1. function getSize(iframe) {
  2. var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document,
  3. body,
  4. html,
  5. height = 0,
  6. width = 0;
  7.  
  8. // from http://stackoverflow.com/questions/1145850/get-height-of-entire-document-with-javascript
  9. doc = doc || document;
  10. body = doc.body;
  11. html = doc.documentElement;
  12.  
  13. height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  14. width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
  15.  
  16. console.log("body.scrollHeight = " + body.scrollHeight + ", body.offsetHeight = " + body.offsetHeight);
  17. console.log("html.clientHeight = " + html.clientHeight + ", html.scrollHeight = " + html.scrollHeight + ", html.offsetHeight = " + html.offsetHeight);
  18.  
  19. return {height: height, width: width};
  20. }

View Demo

Related Posts


回應 (Leave a comment)