Iframe inherit from parent
Solution 1:
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.
Solution 2:
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);
}
Solution 3:
You can always collect all styles to string and set it as innerHTML of style element in iframe.
var selfStyleSheets = document.styleSheets;
var cssString = [];
for (var i = 0, count = selfStyleSheets.length; i < count; i++)
{
var cssRules = selfStyleSheets[i].cssRules;
for (var j = 0, countJ = cssRules.length; j < countJ; j++)
{
cssString.push(cssRules[j].cssText);
}
}
var styleEl = iframe.contentDocument.createElement('style');
styleEl.type = 'text/css';
styleEl.innerHTML = cssString.join("\n");
iframe.contentDocument.head.appendChild(styleEl);