Last active
August 19, 2024 12:00
-
-
Save rekmarks/57b54fec810906dd554b4c8884738536 to your computer and use it in GitHub Desktop.
MessagePort.postMessage() may throw
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
<!-- | |
Proof that cross-realm `MessagePort.postMessage()` can throw. | |
--> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Foo</title> | |
</head> | |
<body> | |
<iframe | |
id="myIframe" | |
srcdoc=" | |
<!DOCTYPE html> | |
<html lang='en'> | |
<head> | |
</head> | |
<body> | |
<script type='module'> | |
console.log('iframe'); | |
let port; | |
window.addEventListener('message', message => { | |
port = message.ports[0]; | |
// MessageEvents are not cloneable, so this will throw. | |
port.onmessage = message => port.postMessage({ echo: message }); | |
}); | |
</script> | |
</body> | |
</html> | |
" | |
></iframe> | |
<script type="module"> | |
const delay = (ms = 100) => new Promise(resolve => setTimeout(resolve, ms)); | |
const { port1, port2 } = new MessageChannel(); | |
port1.onmessage = message => console.log('received message', message); | |
const iframe = document.getElementById('myIframe'); | |
await delay(200); | |
iframe.contentWindow.postMessage(null, '*', [port2]); | |
await delay(100); | |
console.log('sending to iframe'); | |
port1.postMessage(null); | |
console.log('sent'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment