Window postMessage()
Method
Definition and Usage
The postMessage()
method is used to safely enable cross-origin communication.
Syntax
otherWindow.postMessage(message, targetOrigin, [transfer]);
Parameter | Description |
---|---|
otherWindow | A reference to another window, such as the contentWindow property of an iframe, the window object returned by window.open , or a named or numeric indexed window.frames. |
message | The data to be sent to the other window. |
targetOrigin | Specifies which windows can receive the message event, either * (indicating no restrictions) or a URI. |
transfer | Optional, a sequence of Transferable objects to be transferred along with the message. The ownership of these objects will be transferred to the receiver, and the sender will no longer retain ownership. |
Browser Support
Chrome 1 | Edge 12 | Firefox 8 | Safari 4 | Opera 9.5 |
Example
Sender Script
<div>
<input id="text" type="text" value="tutorialpro" />
<button id="sendMessage">Send Message</button>
</div>
<iframe loading="lazy" id="receiver" src="https://c.tutorialpro.org/tutorialprotest/postMessage_receiver.html" width="300" height="360">
<p>Your browser does not support iframes.</p>
</iframe>
<script>
window.onload = function() {
var receiver = document.getElementById('receiver').contentWindow;
var btn = document.getElementById('sendMessage');
btn.addEventListener('click', function (e) {
e.preventDefault();
var val = document.getElementById('text').value;
receiver.postMessage("Hello " + val + "!", "https://c.tutorialpro.org");
});
}
</script>
Receiver Script: https://c.tutorialpro.org/tutorialprotest/postMessage_receiver.html
The receiver script has an event listener for the "message" event and verifies the message origin to ensure it is from a trusted sender.
<div id="recMessage">
Hello World!
</div>
<script>
window.onload = function() {
var messageEle = document.getElementById('recMessage');
window.addEventListener('message', function (e) { // Listen for message event
alert(e.origin);
if (e.origin !== "https://www.tutorialpro.org") { // Verify message origin
return;
}
messageEle.innerHTML = "Message received from " + e.origin + ": " + e.data;
});
}
</script>
- e.source – The source of the message, the sending window/iframe.
- e.origin – The URI of the message source (may include protocol, domain, and port), used to verify the data source.
- e.data – The data sent.