Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE10 does not support stylesheet link in iframe

I have iframe, which loaded dynamically. Content in this iframe should be styled like page on which it's located. To do this I added link to css file to iframe head. It works OK in Firefox, but it doesn't work in IE10. Is it known issue?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="/js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#dialogIframe').load(function(){
                $('#dialogIframe')
                        .contents().find("body")
                        .html("test iframe");
                $('#dialogIframe')
                        .contents().find("head")
                        .html('<link rel="stylesheet" type="text/css" href="/css/main.css">');
            });
        });

    </script>
</head>
<body>
Test
<iframe id="dialogIframe" style="width:300px; height:300px; border: none;">
</iframe>
</body>
</html>

http://jsfiddle.net/YwCRf/

like image 893
Valentina Chumak Avatar asked Jan 30 '26 10:01

Valentina Chumak


2 Answers

innerHTML of head is read-only in IE, the snippet below does the trick:

$('#dialogIframe')
    .contents().find("head")
    .append($('<link rel="stylesheet" type="text/css" href="/css/main.css">')
);

Just in case somebody would need to do this with pure JavaScript, here's the code:

var doc = document.getElementById('dialogIframe').contentWindow.document,
    sheet = doc.createElement('link');
sheet.rel = 'stylesheet';
sheet.type = 'text/css';
sheet.href = '/css/main.css';
doc.documentElement.appendChild(sheet);
like image 87
Teemu Avatar answered Feb 02 '26 03:02

Teemu


My two cents (more browser compatible)

// locate iframe
var frameName = "dialogIframe"; 
var iframe    = document.frames ? document.frames[frameName] : window.frames[frameName];

// create stylesheet    
var ss  = iframe.document.createElement("link");
ss.type = "text/css";
ss.rel  = "stylesheet";
ss.href = "style.css";

// apply to iframe's head
document.all ? iframe.document.createStyleSheet(ss.href) : iframe.document.getElementsByTagName("head")[0].appendChild(ss);
like image 25
Sami Racho Avatar answered Feb 02 '26 03:02

Sami Racho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!