36

Possible Duplicate:
How to apply CSS to iFrame?

Right now I'm loading an iframe via jquery:

 $(window).load(function(){
  $('iframe').load(function() {
      $('iframe').show()
      $('#loading').hide();

    });
    $('#loading').show();
    $('iframe').attr( "src", "http://www.url.com/");

  });

And I have a custom style sheet that I would like to apply to that page. The page within the iframe is not on the same domain, which is why it's tricky. I've found solutions that allow you to add individual tags, but not entire stylesheets.

EDIT: The page in question is loaded via file:// in Mobile Safari so the Cross-domain policy does not apply.

11
  • How the hell did you do that? It should be not allowed because of the cross domain policy of the browsers. Aug 5, 2011 at 17:42
  • Could You add those solutions for individual tags? Aug 5, 2011 at 17:42
  • @KARASZI on the contrary, that's exactly what iframes are for.
    – rockerest
    Aug 5, 2011 at 17:45
  • I'm not understanding why you can't load a stylesheet from the iframe. I did this for a client once the same way you did. I had an ajax window load on the fly and i grabbed the data from serverside and I just embeded the stylesheet into the iframe dynamically.
    – pqsk
    Aug 5, 2011 at 17:48

1 Answer 1

64

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

7
  • 6
    This ought to give security minded people headaches Aug 5, 2011 at 18:04
  • Getting an error with the non-JQ way and no result with the JQ way. Error is Cannot read property "document" of undefined. Aug 5, 2011 at 18:10
  • 4
    Then Cross-domain policy does apply after all Aug 5, 2011 at 18:12
  • @Jacek ahh is that the CDP kicking in? Figured it'd give me a more specific error... Aug 5, 2011 at 18:14
  • 1
    Try that stackoverflow.com/questions/4556429/… Aug 5, 2011 at 18:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.