Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
setupIFrame.js
function setupIFrame(container) {
// create the iframe element
const iFrame = document.createElement('iframe');
iFrame.id = 'styleguide-iframe-' + Math.random().toString(36).substring(2, 10);
iFrame.src = 'about:blank';
iFrame.setAttribute('allowfullscreen', '');
iFrame.setAttribute('frameBorder', '0');
// inject it in the DOM
container.parentNode.insertBefore(iFrame, container);
// store a reference to the iFrame "document" element
const iFrameDocument = iFrame.contentDocument;
// <head>
if (iFrameDocument.head) {
iFrameDocument.head.className = document.head.className;
iFrameDocument.head.innerHTML = document.head.innerHTML;
}
// <body>
if (iFrameDocument.body) {
iFrameDocument.body.className = document.body.className + ' ' + container.className;
// container's children
const children = container.childNodes;
for (let i = 0; i < children.length; i++) {
const cloneChild = iFrameDocument.importNode(children[i], true);
iFrameDocument.body.appendChild(cloneChild);
}
}
// delete the old container
container.remove();
// done
return iFrame;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment