IE浏览器 - IFRAMES / 数据URI

8

我需要在一个沙盒视图中显示内容,主要是完整的html文档(<html>...</html>)。我使用了带有src datauri的沙盒iframe。

var 
  iframe = document.createElement('iframe'),
  content = '<html><head></head><body><h1>Hello</h1></body></html>'
;
iframe.sandbox = '';
iframe.src = 'data:text/html;charset=utf-8,' + content;
document.body.appendChild(iframe);

很不幸,这在Internet Explorer中不受支持... 有什么解决方案/变通方法吗?

2个回答

4

我的解决方案:

  1. 创建一个空的 index.html,只是为了有一个相同源的 iframe。
  2. 通过 javascript 访问 iframe。
  3. 替换其内容。

function ReplaceIframeContentCtrl() {
  var iframe = document.getElementById('test');
  var content = "<html><head></head><body><h1>Hello</h1></body></html>";
  
  iframe.contentWindow.document.open();
  iframe.contentWindow.document.write(content);
  iframe.contentWindow.document.close();
}

document.addEventListener('DOMContentLoaded', ReplaceIframeContentCtrl);
<iframe id="test" src="/index.html"></iframe>


2
只需创建一个空的iframe并替换其内容即可:
function insertIframeHtml(parent, html) {
  const jparent=$(parent).empty();
  const iframe=$('<iframe></iframe>').appendTo(jparent)[0];
  iframe.contentWindow.document.open();
  iframe.contentWindow.document.write(html);
  iframe.contentWindow.document.close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接