Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created June 13, 2012 19:14
Show Gist options
  • Save kara-ryli/2925882 to your computer and use it in GitHub Desktop.
Save kara-ryli/2925882 to your computer and use it in GitHub Desktop.
Write arbitrary HTML into an iframe sandbox. Useful for untrusted 3rd-party code (e.g. ads).
/**
Writes a sandboxed block of HTML to the supplied node.
<p>Based on an example from <a href="https://github.com/RCanine/embed-code">Meebo</a>.</p>
@method writeSandboxedHTML
@namespace RC
@param {String} width a valid CSS width
@param {String} height a valid CSS height
@param {String} html a block of HTML code
@param {HTMLElement} parent a DOM Node within which the block should appear. Defaults to the body element.
@return {HTMLElement} The node containing the HTML block
*/
var RC = window.RC = window.RC || {};
RC.writeSandboxedHTML = function (width, height, html, parent) {
var doc = document,
contentWindow = "contentWindow",
documentS = "document",
iframe = doc.createElement("iframe"),
page = '<!DOCTYPE html><html><head><meta charset="utf-8"><title></title></head><body style="margin:0;padding:0">' + html + '</body></html>',
domainSrc,
parentNode = parent || doc.body,
d;
iframe.frameBorder = "0";
iframe.allowTransparency = true;
iframe.style.width = width;
iframe.style.height = height;
parentNode.appendChild(iframe);
try {
iframe[contentWindow][documentS].open();
} catch (e) {
domainSrc = "javascript:var d=" + documentS + ".open();d.domain='" + doc.domain + "';";
iframe.src = domainSrc + "void(0);";
}
try {
d = iframe[contentWindow][documentS];
d.write(page);
d.close();
} catch (e2) {
iframe.src = domainSrc + 'd.write("' + page.replace(/"/g, '\\"') + '");d.close();';
}
return parentNode;
};
@bjogden
Copy link

bjogden commented Jun 17, 2015

Where is the actual sandboxing of the iframe?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment