【问题标题】:IE - IFRAMES / Data UriIE - IFRAMES / 数据 Uri
【发布时间】:2016-08-22 09:13:05
【问题描述】:
我需要在沙盒视图中显示内容,主要是完整的 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 不支持此功能...
有什么解决方案/解决方法吗?
【问题讨论】:
标签:
javascript
internet-explorer
iframe
data-uri
【解决方案1】:
我的解决方案:
- 创建一个空的
index.html,只是为了拥有同源iframe。
- 通过 javascript 访问 iframe
- 替换其内容
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();
}