Window postMessage()Method
Window Object
Definition and Usage
The postMessage() method is used to safely implement cross-origin communication.
Syntax
otherWindow.postMessage(message, targetOrigin, [transfer]);
| Parameters | 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 numerically indexed window.frames. |
| message | The data to be sent to the other window. |
| targetOrigin | Specifies which windows can receive the message event. Its value can be*(meaning no restrictions) or a URI. |
| transfer | Optional. A list of Transferable objects passed together with the message. Ownership of these objects will be transferred to the receiver of the message, and the sender will no longer retain ownership. |
Browser Support
| Chrome 1 | Edge 12 | Firefox 8 | Safari 4 | Opera 9.5 |
Examples
Sender
<div>
<input id="text" type="text" value="Example" />
<button id="sendMessage" >Send Message</button>
</div>
<iframe id="receiver" src="https://c.example.com/exampletest/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.example.com");
});
}
</script>
Try it »
Receiver: https://c.example.com/exampletest/postMessage_receiver.html
The receiver has an event listener that listens for the "message" event, and we also need to verify the origin of the message to ensure it is 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 the message event
alert(e.origin);
if (e.origin !== "https://www.example.com") { //Verify the message origin
return;
}
messageEle.innerHTML = "from"+ e.origin +"Message received:" + e.data;
});
}
</script>
Try it »
- e.source– The message source, the window/iframe that sent the message.
- e.origin– The URI of the message source (may include protocol, domain, and port), used to verify the data source.
- e.data– The data that was sent.
Window Object Other Extensions