Skip to content

Instantly share code, notes, and snippets.

@bprosnitz
Created May 6, 2015 19:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bprosnitz/89db637b2e798ce05a6a to your computer and use it in GitHub Desktop.
Save bprosnitz/89db637b2e798ce05a6a to your computer and use it in GitHub Desktop.
iframe origin security: dispatchEvent vs postMessage
<script>
window.addEventListener('message', function(event) {
console.log('iframe: Got postmessage in origin ' + location.origin + ' from origin: ' + event.origin + '(' + event.data + ')');
});
window.addEventListener('dispatchToIframe', function() {
console.log('iframe: Got dispatchEvent() in origin ' + location.origin + '(from index.html)');
});
setTimeout(function() {
window.dispatchEvent(new CustomEvent('dispatchFromIframe'));
}, 2000);
setTimeout(function() {
window.postMessage('from iframe', '*');
}, 2000);
</script>
<html>
<body>
<iframe id="origin8081Iframe" src="http://localhost:8081/iframe_contents.html"></iframe>
<iframe id="origin8080Iframe" src="http://localhost:8080/iframe_contents.html"></iframe>
<script>
var eightyOrigin = document.getElementById("origin8080Iframe").contentWindow;
var eightyOneOrigin = document.getElementById("origin8081Iframe").contentWindow;
eightyOrigin.addEventListener('dispatchFromIframe', function() {
console.log('index.html: Got dispatchEvent() to ' + location.origin + ' from localhost:8080');
});
eightyOrigin.addEventListener('message', function(event) {
console.log('index.html: Got postMessage() to ' + location.origin + ' from localhost:8080' + '(' + event.data + ')');
});
eightyOneOrigin.addEventListener('dispatchFromIframe', function() {
console.log('index.html: Got dispatchEvent() to ' + location.origin + ' from localhost:8081');
});
eightyOneOrigin.addEventListener('message', function(event) {
console.log('index.html: Got postMessage() to ' + location.origin + ' from localhost:8081' + '(' + event.data + ')');
});
setTimeout(function() {
eightyOrigin.postMessage('from index.html', '*');
}, 2000);
setTimeout(function() {
eightyOneOrigin.postMessage('from index.html', '*');
}, 2000);
setTimeout(function() {
eightyOneOrigin.dispatchEvent(new CustomEvent('dispatchToIframe'));
}, 2000);
setTimeout(function() {
eightyOrigin.dispatchEvent(new CustomEvent('dispatchToIframe'));
}, 2000);
</script>
</body>
</html>
#!/bin/bash
python -m SimpleHTTPServer 8080 &
S1=$!
python -m SimpleHTTPServer 8081 &
S2=$!
echo "Go to http://localhost:8080"
echo "Once finished, hit enter"
read
kill $S1
kill $S2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment