Last active
February 8, 2019 08:06
-
-
Save makotom/f4b0514fec845b8f33e19bd686349d7e to your computer and use it in GitHub Desktop.
Let's play with window.postMessage()
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 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> |
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 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision to support IE...!