How do I make an <iframe>
inherit its parent's styles and javascript.
I have tried
var parentHead = $("head", parent.document).html(); $("head").html(parentHead);
But, it strips out the <script>
tags. Moreover, I do not see the styles affecting my iframe.
Is there a better/any other approach to this that I'm missing? Thanks.
Short answer: No, iframe s generically can't inherit/access styles/scripts from their parent page. Long answer: You can't change anything in the styles or execute scripts inside an iframe if it's coming from another domain (you can't even read its DOM contents via JavaScript).
It's still possible to access the parent from within a frame provided that the domains match. The variables parent and top can be overwritten (usually not intended). It's safer to use window.
If a user has javascript disabled, iframes will work. An iframe tag has attributes “height” and “width,” which allows the designer great latitude with dimensions and format like 300×250 , 728×90 depending on the Ad size. Iframe tag can appear anywhere on the page and several iframes can be added if wished to.
You can "inherit" the CSS of the parent by having such code in the iframe:
<head> <script type="text/javascript"> window.onload = function() { if (parent) { var oHead = document.getElementsByTagName("head")[0]; var arrStyleSheets = parent.document.getElementsByTagName("style"); for (var i = 0; i < arrStyleSheets.length; i++) oHead.appendChild(arrStyleSheets[i].cloneNode(true)); } } </script> </head>
Worked fine for me in IE, Chrome and Firefox.
Regarding JavaScript, I couldn't find a way to add the parent JavaScript into the iframe directly, however you can add parent.
anywhere to use the JS from within the parent, for example:
<button type="button" onclick="parent.MyFunc();">Click please</button>
This will invoke function called MyFunc
defined in the parent page when the button is clicked.
Here is my "best of" solution to add the styles of the iframe's parent (not the scripts). It works with IE6-11, Firefox, Chrome, (old) Opera and probably everywhere.
function importParentStyles() { var parentStyleSheets = parent.document.styleSheets; var cssString = ""; for (var i = 0, count = parentStyleSheets.length; i < count; ++i) { if (parentStyleSheets[i].cssRules) { var cssRules = parentStyleSheets[i].cssRules; for (var j = 0, countJ = cssRules.length; j < countJ; ++j) cssString += cssRules[j].cssText; } else cssString += parentStyleSheets[i].cssText; // IE8 and earlier } var style = document.createElement("style"); style.type = "text/css"; try { style.innerHTML = cssString; } catch (ex) { style.styleSheet.cssText = cssString; // IE8 and earlier } document.getElementsByTagName("head")[0].appendChild(style); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With