How to create a cross-browser sub document with iframe or shadow dom?

余生长醉 提交于 2019-11-29 09:11:21

To access info from the frame (or write to the frame), it must be in the DOM. It can be hidden, but it still must live in the frames object. JQuery is accessing the iFrame through the frames object and when removed from the dom, it's removed from the frames object

For future reference to anyone stumbling across this question, you can get the encapsulation like so:

$('#iframeGenerator2').contents().find('html').html(frame2HTML);

Here's an example: http://jsfiddle.net/yP34y/4/

In the jsfiddle example, notice everything only works after it's been added to the DOM.

I played around with your fiddle and was able to get it working. I'm using seamless (only Chrome) to make it behave more in line with what you're looking for and I have a CSS fallback for other browsers.

As a note, the iframe needs to be added to the DOM before you start editing it's contents(adding styles and body). You can remove afterwards document.body.removeChild(iframe);.

There is still a lot you can do to make it behave very similarly to a shadow DOM element, this presentation will help you out Seamless iframes: The future, today!

JS

var styles = '<style> .pink { color: pink; width: 100px; height: 100px; } body{background-color:#eee;}</style>';

var html = '<div class="pink">PINK!</div>';

// create iframe
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

//add head and body
iframe.contentDocument.open();
iframe.contentDocument.write(styles);
iframe.contentDocument.write(html);
iframe.contentDocument.close();
iframe.setAttribute('seamless', 'seamless');

//check everything
console.log(iframe);
var head = $(iframe).contents().find('head')[0];
console.log(head);
var body = $(iframe).contents().find('body')[0];
console.log(body);

//remove from DOM
//document.body.removeChild(iframe);

CSS

iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!