JavaScript
Article

Use jQuery to Change CSS on iFrame Content

By Sam Deering

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.

var text = 'hi';
var content = "" + text + "";

var iframe = document.createElement("iframe");
iframe.src = '' +
          'body{margin:0;padding:0;background:transparent}' +
          '';
iframe.open();
iframe.write(css);
iframe.close();

Further thoughts

jquery.frameready.js

frameReady: Remote function calling for jQuery – jquery.frameready.js

Cross Domain Setups that may work

These setups should work and avoid the cross domain issues.

Site 1 – example.com or site1.example.com
Site 2 – site2.example.com

All you need to do is to add this line of JavaScript to both site A and B:

document.domain = 'example.com'

Site 1 – example1.com or site1.example1.com
Site 2 – example2.com

To make this work, you need to create a sub domain called e.g. siteb.example.com. Then point the new sub domain to the IP address of foobar.com. Now both site A and B is located under example.com and you can start to implement solution 1.

Iframe Proxying and hacks

Good article on how to include nested iframes to display content – Read article.
Good article on secure cross domain iframe communication – Read article.

  • http://psdtomagento.com/ PSD to Magento .com

    very nice tutorial, thanks!

  • Thien

    thanks

  • http://twitter.com/RmjNDB Ronald Martin

    it’s really helpful, keep up the good work. Thanks,

  • Sandro Alvares

    Please jquery, javascript pure is bad! thanks

  • Finnt Mc

    How to remove ads form buycraft Free version? Because I have a site form Buycraft, and I have ads all the time! Can someone help me?

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.