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 executing 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 restriction) or a URI. |
| transfer | Optional; a string of Transferable objects passed along with the message. Ownership of these objects is transferred to the receiver of the message, and the sender no longer retains ownership. |
Browser support
| Chrome 1 | Edge 12 | Firefox 8 | Safari 4 | Opera 9.5 |
Example
Sender program
<
div
<input id="text" type="text" value="Runoob" />
<button id="sendMessage">Send the message
button
div
<iframe id="receiver" src="https://c.runoob.com/runoobtest/postMessage_receiver.html" width="300" height="360">
<p>Your browser does not support iframe.
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.runoob.com"); }); }
script
Try it »
Receiver program: https://c.runoob.com/runoobtest/postMessage_receiver.html
The receiver program has an event listener that listens for the "message" event, and we also need to verify the message source address 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.runoob.com
"
)
{
//
Verify the message source address
return
;
}
messageEle
.
innerHTML
=
"
From the
"
e
.
origin
"
Message received:
"
e
.
data
;
}
)
;
}
script
Try it »
- e.source - the message source, the sending window/iframe of 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