我正在尝试将带有 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>
最佳答案
抱歉,没有足够的代表直接发表评论。
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);
关于javascript - 将 HTML 动态加载到 iframe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871330/