How to Inject Custom HTML and CSS into an iframe
videos

How to Inject Custom HTML and CSS into an iframe

Tutorial Details
    • Difficulty: Moderate
    • Format: Screencast

Ever been to a site like JSBin, where you can write HTML, CSS, and JavaScript, and then see the results in a panel to the right? An iframe is how we can accomplish this task. In today’s quick tip, I’ll show you how to inject HTML and CSS into an iframe.

Select 720p for optimal viewing.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.google.com Eric E. Schmidt

    Yay first!

    • Kristof

      I am utterly envious…

  • http://rikdevos.com/ Rik de Vos

    Great screencast as always Jeffrey!

    One thing though, wouldn’t it be better to set the variable styleTag using the following code:

    styleTag = $(”).appendTo( contents.find(‘head’) );

    I would use a method like this because you won’t have to wait on jQuery to append the html (which can sometimes take a little while) before parsing.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Hey Rik – Yeah, just left a comment on the YouTube page about doing that instead. The GitHub repo reflects that. :)

  • Potado

    Quite a fun little tip! I quite like Internet Explorer’s way of subtracting from the width when adding padding or whatever.

  • http://jinxed.com.hr Jinxed

    Demo doesn’t work. I liked tip with web kit box sizing, I’d like to see more of such tips .)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      What browser are you on?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Oh sorry. Stupid S3 permissions mistake. The demo is all fixed now.

  • Johannes

    Is there a version of Livereload for Windows 7 and Chrome?

  • Darren

    Nice I can make a custom WYSIWYG now.

  • http://visudex.co.cc Jeremy MICHEL

    Thanks for the tutorial. Do you know how to add the syntax highlighting on the textareas?

  • alex

    is it me or does the demo not work?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Try it again. Was a permissions issue.

      • Matis

        What’s the name of your theme for sublime text?

  • http://www,facebook.com/ Mark Zuckerberg

    Could this possibly be used to skin the facebook plugins?

    • Michael

      it has to be on the same domain, the browser doesn’t allow to modify iframes on domains, which does not seems to be the same as the source is.

  • Brad

    Excellent tut, useful for practicing scripts and other things without messing pages up

  • Felix Guerrero

    I love rapid tools for prototyping, I will hack this to my classes at the School. This is very helpful, thanks Jeff.

  • Kyle Smith

    Just a heads up, looks like you left your local reference to the livereload script on line 25. Not sure if that was intentional or not.

  • http:/www.resumebaking.com Aleksey Asiutin

    Hi Jeffrey.

    Cool stuff, but it has a little bit overloading:

    $(‘textarea’).focus(function() {
    var $this = $(this);
    $this.keyup(function() {
    if ( $this.attr(‘id’) === ‘html’) {
    body.html( $this.val() );
    } else {
    // it had to be css
    styleTag.text( $this.val() );
    }
    });
    });

    By executing this javascript you are attaching ‘keyup’ events every time you are focusing on the textarea element.
    Try to add some logging

    $(‘textarea’).focus(function() {
    var $this = $(this);
    $this.keyup(function() {
    if ( $this.attr(‘id’) === ‘html’) {
    body.html( $this.val() );
    console.log(‘event fired ‘+ new Date());
    } else {
    // it had to be css
    styleTag.text( $this.val() );
    console.log(‘event fired ‘+ new Date());
    }
    });
    });

    then try to switch between textareas couple of times and you will see how many events are attached.

    It can be fixed by removing focus event listener:

    $(‘textarea’).keyup(function() {
    var $this = $(this);
    if ( $this.attr(‘id’) === ‘html’) {
    body.html( $this.val() );
    } else {
    // it had to be css
    styleTag.text( $this.val() );
    }
    });

    Maybe this focus event helps us to prevent some issues. if so, please tell about it.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Ahh yes – of course you’re right. I’m trying to remember why I thought I needed to listen for focus… Anyhow, the source and demo have been updated. Good eye.

  • http://www.github.com/dotink Matthew J. Sahagian

    There’s a few things you could do to achieve the equal heights you were going for without relying on JS.

    Both of them only work certain circumstances, the first is to apply some ridiculous amount of padding to the bottom, and then a negative bottom margin of equal value. So long as the parent has overflow hidden, the excess padding will get cut off.

    aside {

  • http://www.github.com/dotink Matthew J. Sahagian

    Whoops, accidental submit:

    aside {
    float: right;
    padidng-bottom: 10000em;
    margin-bottom: -10000em;
    }

    The case where this is limited is if you want a bottom border (as obviously it will be beyond the bottom of the parent element. It is also limited if there’s any chance that you would have content stretching beyond that padding.

    The other method, which would work pretty well for what you have here is absolutely positioning it and defining all directional positions:

    aside {
    position: absolute;
    left: 50%;
    top: 0;
    right: 0;
    bottom: 0;
    }

    This will cause the element to expand to fit the entire area — and will scale quite appropriately too.

  • Sachit

    How can i apply custom css to an iframe that is on a different domain?

  • http://www.studiobrahma.in vinit pratap singh

    Excellent… that a lot.. here my search end over iframe. thanks

  • http://www.logicdesign.co.uk/ Suffolk Web Design

    Fantastic, I genuinely was trying to figure this out a couple of days ago. We do a fair bit of affiliate marketing and the content supplied by networks often come in an iFrame but the contents of the frame look awful, now we can add in css into the header!

    Thanks for the post

  • Jose Gomez

    src=”http://localhost:35729/livereload.js” <– what does this script do?

  • guzman

    not work in IE6
    “invalid argument”

    ¿try catch block ?

    (function() {
    $(‘.grid’).height( $(window).height() );

    var contents = $(‘iframe’).contents(),
    body = contents.find(‘body’),
    try
    {
    //Run some code here
    styleTag = $(”).appendTo(contents.find(‘head’));
    }
    catch(err)
    {
    //Handle errors here
    }

    $(‘textarea’).keyup(function() {
    var $this = $(this);
    if ( $this.attr(‘id’) === ‘html’) {
    try
    {
    //Run some code here
    body.html( $this.val() );
    }
    catch(err)
    {
    //Handle errors here
    }

    } else {
    try
    {
    //Run some code here
    // it had to be css
    styleTag.text( $this.val() );
    }
    catch(err)
    {
    //Handle errors here
    }

    }
    });

    })();

    .

  • Xander

    Great, but why? It would be great if you could alter content of an iframe located on a different server.
    But never give up your dreams.

  • http://maomuffy.blogspot.com/ Mfawa Alfred Onen

    You always never fail to impress…great tutorials!

  • supprof

    you always have been the best
    thank you very mutch jeffy way

  • http://brianswebdesign.com Brian Temecula

    I don’t use a whole lot of iframes, but this is pretty sweet.

  • http://www.videowatchr.com/ Richard G

    Very nice.
    Been looking at ways to do this and your article is right on the spot.

    I added it on my blog http://tumblr.com/ZIRu3yCGZEOW

  • http://creativemanner.com Ozgur Corulu

    Thanks for the cast Jeffrey. Its a fun tool to play with :)

  • http://www.mauromarano.it mauro

    What’s the theme you are using with sublime text 2? It’s really nice

  • http://www.web4you.co.in Deven

    Can we insert HTML elements to iFrame if the iframe consist other domain URL like google.com ? Please advice.

    Thank you for the nice tips.

  • http://www.bandil.tk Machfudz

    Nice info…
    I just know that we can inject them in iframe…
    nice..

  • http://techably.com/ Rahul

    Nice tut. I’ve implemented this before but not as good as you told in the video. Thanks a lot.

  • http://www.whoisandy.in Andy

    Hey, Jeff, Great screencast, I was waiting for this !!!

    I`m able to add syntax highlighting using codemirror.
    Is there a way to add a textexpander feature to this ?

    I`ve tried it but it fails. Tried to read one line of the textarea at a time and compare it with a predefined values in a json file. but it replaces the complete line.

    I want some thing like, I type html and press tab, the whole thing should be autocompleted.

    Can this be done ? if so how ?

  • http://www.ariona.net Rian Ariona

    As usual, Nice tutorial Jeff!

    i have a question, how we style iframe content, from different domain?
    for example, take a look at http://www.omgubuntu.co.uk , and head into facebook like box, actually it is a facepile plugin, but omgubuntu had modified it.

  • http://jarodonline.wordpress.com Jarod Billingslea

    I never comment, but this is really good to see. I was just trying to figure out how to inject code into an iframe earlier (which I successful did, after so many hours of stress).

    Glad to know this makes things simpler for people like myself.

  • http://odedharth.com Oded

    Thanks for the great tutorial!

    What is that mac os plugin/tool/extension that lets organize the open windows (when clicking on the green expand button) ?

  • http://triskelwebdesign.com Caio

    It really helped me to solve some issues, thank you!

  • John

    Nice article

  • matiz

    can someone tell me the name of color scheme on this video? (for sublimetext 2)

  • Edward Longman

    Pleased with my self for spotting your only mistake as you made it,

    Excellent

  • matiz

    https://github.com/buymeasoda/soda-theme here is the name of the color theme used on this video (for sublime)

  • Albert

    Hi there,
    Thanks for the tut!

    I was wondering if there is a possibility to load a css file to the iframe. I’ve been trying this:

    styleTag.text( ‘<link rel="stylesheet" href="http://example.com/global.css&#039; );

    But seems to break down and it only shows: “‘ ); }); })();”

    Thanks,
    Albert.

    • Sergey

      You are appending this to tag, try appending this to the tag instead.

  • Sergey

    You are appending this to <style> tag, try appending this to the <head> tag instead.

  • Cosmin

    I’m trying to implement syntax highlighting into the textarea wjtb codemirror but it’s not working as it should.
    I’m a beginner when it comes to javascript and jQuery, I kept trying and I’m not getting the right result.
    I don’t know where to place it to work. The codemirror library is new to me also, kind of confusing when put all together.

  • http://triskelwebdesign.com SP Web Design

    Thank you! I might start back using iframes with this!

  • http://codepsd.com/ CodePsd

    I am trying to extend this one from the Jeffrey Ways code. See it here -> http://codepsd.com/editor/
    Is someone willing to help me?

  • http://www.electroreview.ro ER

    Thank you. Very usefull, didn’t know that it’s possible.

  • sinun

    Hi

    Very interesting stuff. I found http://localhost:35729/livereload.js. in your code. What exactly is it for? Do I need it to download?

  • Ben

    Nice introduction, Jeffrey!
    I placed two keyup events on each textarea directly. Littl’ bit shorter

    $(‘#html’).keyup(function(){
    body.html(this.value);
    });

    $(‘#css’).keyup(function(){
    styletag.text(this.value);
    });

  • http://blog.pathtosharepoint.com Christophe

    Thanks! And I like the live style of the tut, with real time debugging :-)

  • Azzoth

    If there is a head tag in the html textarea is there a way to inject what’s inside this head tag in the head tag of the iframe ? I tried to add a find to the .val but it doesn’t works. Is there a way to do that ?

  • http://www.alignmyviews.com Dheeraj

    Really grt post for doing big things with small ideas (creativity).
    thanks jeffrey :)