Add CSS to iFrame

112,600

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

Share:
112,600
Peter Kazazes
Author by

Peter Kazazes

I'm a full stack platform developer, public speaker, and strategist. Beginning with iOS development as teenager in my bedroom (and much help from SO), I built the first social-media-sourced polling platform, Twelect, which I transformed into Sibyl Vision, a predict-anything public opinion analysis firm. I regularly speak about Sibyl's research at universities and on national television. These days, I build real-time data abstraction platforms which spotlight actionable business intelligence. I've built software for some of the country's largest institutions, and am obsessed with evolving digital policy and information security.

Updated on June 29, 2020

Comments

  • Peter Kazazes
    Peter Kazazes almost 4 years

    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.

  • Vivian River
    Vivian River over 12 years
    This ought to give security minded people headaches
  • Peter Kazazes
    Peter Kazazes over 12 years
    Getting an error with the non-JQ way and no result with the JQ way. Error is Cannot read property "document" of undefined.
  • Jacek Kaniuk
    Jacek Kaniuk over 12 years
    Then Cross-domain policy does apply after all
  • Peter Kazazes
    Peter Kazazes over 12 years
    @Jacek ahh is that the CDP kicking in? Figured it'd give me a more specific error...
  • Jacek Kaniuk
    Jacek Kaniuk over 12 years
  • ᴍᴀᴛᴛ ʙᴀᴋᴇʀ
    ᴍᴀᴛᴛ ʙᴀᴋᴇʀ about 9 years
    Any way to stop the flicker whilst the stylesheet is applied?
  • Frederico Schardong
    Frederico Schardong almost 9 years
    Does that work on IE8? I am trying to inject a CSS file but IE8 is not processing it. It works on IE11 using the compatibility mode, though.