Use jQuery to Change CSS on iFrame Content

Sam Deering
Share

In this post, I have also included some documentation of failed attempts on trying to change the CSS of iframed content on a different domain. Also some information on how to change css in an iframe on same domain, which (as far as I know) can’t be done without a proxy pass or such.

Cross domain Efforts

How it works:

Compared URL Outcome Reason
http://www.example.com/dir/page.html Success Same protocol and host
http://www.example.com/dir2/other.html Success Same protocol and host
http://www.example.com:81/dir/other.html Failure Same protocol and host but different port
https://www.example.com/dir/other.html Failure Different protocol
http://en.example.com/dir/other.html Failure Different host
http://example.com/dir/other.html Failure Different host (exact match required)
http://v2.www.example.com/dir/other.html Failure Different host (exact match required)

Insert iFrame:



Ways to to change CSS in an iframe
Some of these work, and some don't but i've included both for you to ponder amd make up your own decisions.

This method didn't work for me.
[js]
var text = 'hi';
var content = "" + text + "";

var iframe = document.createElement("iframe");
iframe.src = ' document.body.appendChild(iframe);

var doc = iframe.document;
if(iframe.contentDocument)
doc = iframe.contentDocument; // For NS6
else if(iframe.contentWindow)
doc = iframe.contentWindow.document; // For IE5.5 and IE6
// Put the content in the iframe
doc.open();
doc.writeln(content);
doc.close();

doc.getElementsByTagName("body").style.backgroundColor = 'red';

This method didn’t work for me.

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

This method worked for me.

var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);

This method worked for me.

var iframe = top.frames[name].document;
var css = ” +