动态加载HTML和iframe

时间:2015-06-16 15:01:23

标签: javascript jquery html iframe

我尝试动态地将带有HTML的iframe添加到现有页面。我已经得到了iframe加载和显示。但是" Body" iframe没有显示。有帮助吗?

<html>
<head>
<script>
window.onload = function() {
                var iframe = document.createElement('iframe');
                var html =
                    '<html><head>' +
                        '<scr' + 'ipt src="https://localhost:44302/foo.js"></scr' + 'ipt>' +
                        '<scr' + 'ipt src="https://localhost:44302/bar.js"></scr' + 'ipt>' +
                    '</head>' +
                    '<body>Hi</body></html>';
                iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
                document.body.appendChild(iframe);
                console.log('iframe.contentWindow =', iframe.contentWindow);
            }
</script>
</head>
<body></body>
</html>

https://jsfiddle.net/0m5axpxx/2/

1 个答案:

答案 0 :(得分:3)

抱歉,没有足够的代表直接评论。

var iframe = document.createElement('iframe');
var html =
    '<html>' + 
    '<head>' +
    '<scr' + 'ipt src="https://localhost:44302/oidc.js"></scr' + 'ipt>' +
    '<scr' + 'ipt src="https://localhost:44302/requestToken.js"></scr' + 'ipt>' +
    '</head>' +
    '<body>Hi</body>' + 
    '</html>';

iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);

你在jsfiddle中的例子,'script'的第二行,被错误输入srcipt,修复它并且它有效。 JsFiddle

var iframe = document.createElement('iframe');
var html =
    '<html>' + 
    '<head>' +
    '<scr' + 'ipt src="https://localhost:44302/oidc.js"></scr' + 'ipt>' +
    '<scr' + 'ipt src="https://localhost:44302/requestToken.js"></scr' + 'ipt>' +
    '</head>' +
    '<body>Hi</body>' + 
    '</html>';

iframe.srcdoc = html;
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);