Skip to content

Instantly share code, notes, and snippets.

@kylewelsby
Last active October 10, 2016 23:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylewelsby/585b3a5395c6731acc50 to your computer and use it in GitHub Desktop.
Save kylewelsby/585b3a5395c6731acc50 to your computer and use it in GitHub Desktop.
postMessage Example
<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