Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created July 29, 2022 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/b7e924c7c8c7477b021c110545cc602a to your computer and use it in GitHub Desktop.
Save bellbind/b7e924c7c8c7477b021c110545cc602a to your computer and use it in GitHub Desktop.
[JavaScript][HTML] run es modules in iframe context
<!doctype html>
<html>
<head>
<script type="module">
document.querySelector("#run").addEventListener("click", async ev => {
const modUrl = new URL("./module.js", location.href).href;
//console.log(modUrl);
const iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.append(iframe);
const win = await iframe.contentWindow.eval(
`import("${modUrl}").then(mod => Object.assign(globalThis, mod));`);
console.assert(win === iframe.contentWindow, "win === iframe window");
alert(iframe.contentWindow.add(1, 2)); // example
iframe.remove();
});
</script>
</head>
<body>
<button id="run">run es modules in iframe context</button>
</body>
</html>
// es module example with top level await
export const add = await ((a, b) => a + b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment