Created
July 29, 2022 14:13
-
-
Save bellbind/b7e924c7c8c7477b021c110545cc602a to your computer and use it in GitHub Desktop.
[JavaScript][HTML] run es modules in iframe context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
demo: https://gist.githack.com/bellbind/b7e924c7c8c7477b021c110545cc602a/raw/index.html