1

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/

1
  • '<scr' + 'ipt looks like XSS Commented Nov 15, 2015 at 9:01

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use the srcdoc attribute instead of src to avoid web-kit cross-domain issues. See here: stackoverflow.com/a/22748658/265877

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.