Last active
October 10, 2016 23:20
-
-
Save kylewelsby/585b3a5395c6731acc50 to your computer and use it in GitHub Desktop.
postMessage Example
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
<html> | |
<head> | |
<script> | |
var count=0; | |
function sendMessage() { | |
window.parent.postMessage( | |
JSON.stringify({"greeting": "hello world"}), // A stringified message to send. | |
"*" // The intended origin, in this example we use the any origin wildcard. | |
); | |
} | |
setInterval(function(){ | |
sendMessage(); // Send a message every second | |
},1000); | |
window.onmessage = function(e){ | |
if(e.origin === window.location.origin){ | |
return; | |
} | |
if(!e.data){ | |
throw new Error('Message event contains no readable data.'); | |
} | |
console.log(e.data); | |
var elm = document.createElement('li'); | |
elm.innerHTML = e.data; | |
var out = document.getElementById('messages'); | |
out.appendChild(elm); | |
} | |
</script> | |
</head> | |
<body> | |
<p>child window on different domain <a href="https://gist.github.com/kylewelsby/585b3a5395c6731acc50">GitHub Gist</a></p> | |
<ol id="messages"></ol> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment