22

I often see sites using iframes containing an external site, and a top frame containing JavaScript functionality for the user.

e.g. user analytics software, Digg bar, etc...


Any tips for experimenting on something similar? =) Would be awesome to know

RadiantHex
  • 24,907
  • 47
  • 148
  • 244

3 Answers3

31

No, not from outside the iframe. An <iframe> is its own world. If the domains etc. match, then Javascript can communicate in and out, and could (if it wanted to) inject CSS into a child frame.

If the <iframe> contains content from a different domain, there's pretty much nothing you can do. The parent page controls the size of the frame and whether it's visible, and can put its own content over the frame by positioning etc, but it can't directly effect the way the actual frame content is rendered.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • thanks so much! What if the domain is the exact same as the host page? – RadiantHex Jul 20 '10 at 11:46
  • 2
    If you're on the same domain, then Javascript from the parent page can mess with the contents of the frame. The parent page CSS won't affect the frame page, but Javascript can change the CSS or change element styles etc. – Pointy Jul 20 '10 at 13:34
  • is there anyway to do this using some techniques people are saying.. embedding a child iframe or postMessage or something? http://pipwerks.com/2008/11/30/iframes-and-cross-domain-security-part-2/ http://johan.driessen.se/posts/resizing-cross-domain-iframes – Steve Robinson Jul 25 '13 at 07:43
4

If it is of same domain you can interfere the iframe content using javascript as follows.. assume id of iframe is IframeId. And you want to change color of element having id "elementId".

$("iframe").load(function() {
   var frameContents;
   frameContents = $("#IframeId").contents(); 
   frameContents.find("#elementId").css("color","#fff");
});
Joshua Terrill
  • 1,995
  • 5
  • 21
  • 40
0

This can be accomplished by injecting the CSS link to the Header of the iframe:

    // this function will inject the link to CSS into iframe header
    function loadCSSToiFrame(iframeId, filename){ 
       var file = document.createElement("link");
       file.setAttribute("rel", "stylesheet");
       file.setAttribute("type", "text/css");
       file.setAttribute("href", filename);
       document.getElementById(iframeId).contentWindow.document.head.appendChild(file);
    }
  
    // just call a function to load your CSS
    // this path should be relative your HTML location
    loadCSS("iframe_id", "stylesheet.css");
Andrey
  • 349
  • 4
  • 4