Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ilearnjavascript/9d4855b9a189b1144d675c1cb8f52179 to your computer and use it in GitHub Desktop.
Save ilearnjavascript/9d4855b9a189b1144d675c1cb8f52179 to your computer and use it in GitHub Desktop.
plainjs - window.postmessage and iframes - 7.html
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>window</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>window</h1>
<div id="outerContainer"></div>
<iframe width="500" height="250" src="http://127.0.0.1:8080/iframe.html"></iframe>
<script>
// function that gets triggered when message event is triggered
function receiveMessage(event) {
if( event.origin === "http://127.0.0.1:8080"
&& event.data === "message from iframe"
&& event.data.length === 19
&& typeof event.data === 'string') {
console.log("event.origin: ", event.origin);
console.log("event.data: ", event.data);
console.log("event.source: ", event.source);
document.getElementById("outerContainer").innerText = `
Message from iFrame:
event.origin: ${event.origin}
event.data: ${event.data}
event.source: ${event.source}
// open also console to inspect objects
`
// I delayed the response only for the effect
setTimeout(function() {
event.source.postMessage("message from window", event.origin);
}, 1000);
}
}
// event listener for message event
window.addEventListener("message", receiveMessage, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment