Skip to content

Instantly share code, notes, and snippets.

@jae-jae jae-jae/iframe-sandbox.js

Last active Aug 27, 2017
Embed
What would you like to do?
create iframe and append page HTML to iframe 动态创建iframe沙箱
/**
* Create Iframe
*
* Author: Jaeger <JaegerCode@gmail.com>
*
* */
(function(global){
global.iframe = {
create:function (dom,content){
var tpl = '<iframe src="about:blank" style="width:100%;height:100%;border:0px;display: block!important;"></iframe>';
dom.innerHTML = tpl;
var iframeDom = dom.children[0];
this.write(iframeDom,content);
return iframeDom;
},
write: function (iframeDom, content) {
if (iframeDom.tagName && "iframe" == iframeDom.tagName.toLowerCase()) {
var c = iframeDom.contentWindow.document;
try {
c.open(), c.write(content), c.close()
} catch (d) {
console.log("append HTML to [iframe:" + iframeDom.name + "] ERROR!")
}
}
}
};
})(window);

html

<div id="app" style="height: 500px;width: 800px">
<!--  insert iframe -->
</div>

js

fetch('http://xxx.com/index.html').then((r)=>{
  return r.text();
}).then((html)=>{
  var a = document.querySelector('#app');
  iframe.create(a,html)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.