970_90

Friday, 15 April 2016

How to apply css in iframe with javaScript?

How to apply css in iframe with javaScript?

See Following Working Example:
Suppose you have Following Iframe
<iframe border="0" cellspacing="0" frameborder="0" id="myIframeWebsite" name="myIframeWebsite" src="http://example.com/mydir/file.html"></iframe>

Now you just need to add a script code which will add the css file in iframe.
For Example:
<iframe border="0" cellspacing="0" frameborder="0" id="myIframeWebsite" name="myIframeWebsite" src="http://example.com/mydir/file.html"></iframe>
<script type="text/javascript">
var iframeCssLink = document.createElement("link") 
iframeCssLink.href = "/css/myiframecss.css"; 
iframeCssLink.rel = "stylesheet"; 
iframeCssLink.type = "text/css"; 
frames['frame1'].document.body.appendChild(iframeCssLink);
</script>

What will do above code
Whenever iframe load in browser, "/css/myiframecss.css" file will will be added in the head of iframe.
You just need to add all the css inside "/css/myiframecss.css"


Note: Iframe and website must have same Domain, Port and protocol.