Embedding Reactjs in Remote Site iFrame

To satisfy the Same Origin policy (prevent CORS errors), set the <iframe>'s srcdoc attribute instead of trying to write to it.

n.srcdoc = "\n    <!doctype html>\n    <head><script src='http://localhost:3001/static/js/bundle.js' type='text/javascript'></script></head>\n    <body><div id='root'></div></body>\n    </html>";

As an added bonus, you can disable the right-click context menu with:

n.contentWindow.document.addEventListener("contextmenu", function(e){
    e.preventDefault();
    return false;
}, false);

This is completely useless as a security measure, but it's only there as a red herring. The page that shows when you open the frame on its own will not contain the content. Only do this if there's nothing in the iframe's page that the user will want to copy; it doesn't stop them from doing so, but it's really irritating if you do want to copy something.


Demo:

//Creates Div
var d = document.createElement("div");
document.body.appendChild(d);

//Creates iFrame
var n = document.createElement("iframe");
n.id = "microcom-frame";
n.style.width = "100%";
n.style.height = "100%";
n.style.background = "transparent";
n.style.position = "relative";
n.style.margin = 0;
n.style.border = "none";
n.style.overflow ="hidden";
n.style.display = "block";

//Append iFrame inside Div
d.appendChild(n);

//Write content to iFrame
n.srcdoc = "<!doctype html><html><head></head><body><div id='root'>Example content</div></body></html>";