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…
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
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.