【问题标题】:Dynamically loading HTML into and iframe将 HTML 动态加载到 iframe 中
【发布时间】:2015-11-15 16:36:15
【问题描述】:

我正在尝试将带有 HTML 的 iframe 动态添加到现有页面。我已经让 iframe 加载和显示。但是 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/

【问题讨论】:

  • 'XSS

标签: javascript jquery html iframe


【解决方案1】:

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

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 中的示例,即“脚本”的第二行,输入错误为 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);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多