Skip to content

Instantly share code, notes, and snippets.

@makotom
Last active February 8, 2019 08:06
Show Gist options
  • Save makotom/f4b0514fec845b8f33e19bd686349d7e to your computer and use it in GitHub Desktop.
Save makotom/f4b0514fec845b8f33e19bd686349d7e to your computer and use it in GitHub Desktop.
Let's play with window.postMessage()
<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<title>Master</title>
<script>
window.addEventListener('DOMContentLoaded', function () {
document.querySelector('#triggerBtn').addEventListener('click', function () {
const slaveWindow = window.open('slave.html');
window.addEventListener('message', function (evt) {
if (evt.source === slaveWindow && evt.origin /* In production, specify valid FQDN for security purposes */) {
slaveWindow.postMessage('hoge', '*' /* In production, specify valid FQDN for security purposes */);
}
});
});
});
</script>
<button id="triggerBtn" type="button">Click me!</button>
<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<title>Slave</title>
<script>
window.addEventListener('load', function () {
if (window.opener !== null) {
window.opener.postMessage('hoge', '*' /* In production, specify FQDN for security purposes */);
}
});
window.addEventListener('message', function (evt) {
if (evt.source === window.opener && evt.origin /* In production, assert FQDN for security purposes */) {
document.querySelector('body').appendChild(document.createTextNode(evt.data));
}
});
</script>
<p>I'm slave.</p>
@makotom
Copy link
Author

makotom commented Feb 8, 2019

Revision to support IE...!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment