2015-06-16 85 views
0

我試圖動態地將HTML添加到現有頁面。我已經獲得了加載和顯示的iframe。但是iframe的「Body」沒有顯示。任何幫助?將HTML動態加載到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/

+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例如,「腳本」,二號線被錯誤地輸入到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);

+1

你可以還可以使用'srcdoc'屬性而不是'src'來避免web-kit跨域問題。看到這裏:http://stackoverflow.com/a/22748658/265877 – Alex