Page 55 - JavaScript
P. 55
Chapter 2: .postMessage() and MessageEvent
Syntax
• windowObject.postMessage(message, targetOrigin, [transfer]);
• window.addEventListener("message", receiveMessage);
Parameters
Parameters
message
targetOrigin
transfer optional
Examples
Getting Started
What is .postMessage(), when and why do we
use it
.postMessage() method is a way to safely allow communication between cross-origin scripts.
Normally, two different pages, can only directly communicate with each other using JavaScript
when they are under the same origin, even if one of them is embedded into another (e.g. iframes)
or one is opened from inside the other (e.g. window.open()). With .postMessage(), you can work
around this restriction while still staying safe.
You can only use .postMessage() when you have access to both pages' JavaScript code.
Since the receiver needs to validate the sender and process the message accordingly, you can
only use this method to communicate between two scripts you have access to.
We will build an example to send messages to a child window and have the messages be
displayed on the child window. The parent/sender page will be assumed to be http://sender.com
and child/receiver page will be assumed to be http://receiver.com for the example.
Sending messages
https://riptutorial.com/ 12

