JSFiddle - React, Tailwind, and code Playground
HTML
<iframe height="200" sandbox="allow-same-origin allow-scripts"></iframe>
JavaScript
// From parent we fetch both frame1.html and frame2.html
const frame1Content = `
<h1>I am frame 1</h1>
<!-- Below src will be replaced by the top window -->
<iframe src="frame2.html" sandbox="allow-same-origin"></iframe>
<script>
const frame = document.querySelector("iframe");
onload = e => frame.contentDocument.body.append("frame 1 can access frame 2");
parent.document.body.append("Oops frame 1 can access parent"); // cross-origin, won't happen
<\/script>`;
const frame2Content = `
<h1>I am frame 2</h1>
<script>
document.body.append("Oops, I'm running scripts");
<\/script>`;
const frame = document.querySelector("iframe");
// We can't have `"` in the content since we use it for the attribute
const cleanFrame2Content = frame2Content.replace(/"/g, "\\\"");
// Replace the src attribute by the actual content of frame2.html
const cleanFrame1Content = frame1Content.replace(`src="frame2.html"`, `srcdoc="${cleanFrame2Content}"`);
frame.src = `data:text/html,${encodeURIComponent(cleanFrame1Content)}`