window.postMessage() is available to all windows (including the current window, popups, iframes, and frames) that allows you to send textual messages from your current window to any other - regardless of any cross-domain policies that might exist.
window.postMessage("string") method generates a message DOM event on the document of the receiving document. This event object contains the message as a property: event.data which the receiving document can use however they see fit.
The demo demonstrates how easy it is for two iframe of different origins to talk to each other.
window.document.onmousemove = function(e) {
var x = (window.Event) ? e.pageX : window.event.clientX;
var y = (window.Event) ? e.pageY : window.event.clientY;
// this send data to the second iframe of the current page
window.parent.frames[1].postMessage('x = ' + x + ' y = ' + y, '*');
};
var onmessage = function(e) {
var data = e.data;
var origin = e.origin;
document.getElementById('display').innerHTML = data;
};
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', onmessage);
}
Security Issues
<div id="test">Send me a message!</div>
<script>
document.addEventListener("message", function(e){
document.getElementById("test").textContent =
e.domain + " said: " + e.data;}, false);
</script>
1. If you're expecting a message from a specific domain, set of domains, or even a specific url, please remember to verify the .domain or .uri properties as they come in, otherwise another page will be bound to spoof this event for malicious purposes.
2. Just because a string is coming in, as a message, doesn't mean that it's completely safe. Note that in the example, above, I inject the string using .textContent, this is intentional. If I were to inject it using .innerHTML, and the message contained a script tag, it would execute immediately upon injection. This is a critical point: You'll need to be sure to purify all your incoming messages before they are used and injected into the DOM.
Read more >>