简体   繁体   中英

Dynamically loading HTML into and iframe

I'm trying to dynamically add an iframe with HTML to an existing page. I have gotten the iframe to load and show. However the "Body" of the iframe does not show. Any help?

<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/

Sorry, not enough rep to directly comment.

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);

Your example in jsfiddle, the 2nd line of 'script', is mistyped to srcipt , fix it and it works. 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM