Inject a string into an iframe?

I have run across a situation where i have an iframe which loads a webpage from a file. I need to be able to inject a css file and a js file into the iframe, so that when the site is being viewed through the iframe, these css rules and script will be applied, but if the site is viewed outside of the iframe, by just navigating to the file thats loaded into the iframe for example, the css and js file don’t get loaded…

Is this possible?

Yes, it it perfectly possible. You can access the contentDocument, assuming that it has an id of ‘localFromFile’ with:


var iframe = document.getElementById('localFromFile'),
    iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

Then with access to that document, you can use the following function to inject a style tag in to a head section.


function addcss(css, document) {
    document = document || window.document;

    var head = document.getElementsByTagName('head')[0],
        s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    if (s.styleSheet) { // IE
        s.styleSheet.cssText = css;
    } else {
        s.appendChild(document.createTextNode(css));
    }
    head.appendChild(s);
}

And you can make use of the above function as follows:


addcss('css/customcss.css', iframeDocument);

thanks for the reply…

It doesn’t seem to be working for me though :frowning:

The iframe is loading the page fine but the css file still not being loaded where ive called the iframe localfromfile by id and changed the path to the css file when the function is called.

Having a look through the code in the iframe, it isn’t being injected

There’s a couple of stumbling blocks here.

First, the addcss function is for adding a css declaration to the page, not an actual css file. That can be done with the following simpler function:


function addcssfile(cssfile, document) {
    document = document || window.document;
 
    var head = document.getElementsByTagName('head')[0],
        link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet')
    link.setAttribute('type', 'text/css')
    link.setAttribute('href', cssfile)
    head.appendChild(link);
}

And second, you need to wait until the iframe has been loaded before you will be able to make changes to the iframe itself, which can be done by waiting for the iframe’s onload event, or by using more modern techniques to wait until the iframe’s DOM is ready to be worked with.