PostMessage is a method in JavaScript that enables communication between web pages hosted on different domains. It allows scripts running on one page to send messages to scripts running on another page, even if they are hosted on different servers or domains.
The basic syntax for the PostMessage method is as follows:
window.postMessage(message, targetOrigin, transferable);
Here's a breakdown of each parameter:
message
: This is the message that you want to send from one script to another.
It can be any value, including strings, objects, or structured data.targetOrigin
: This parameter specifies the URL of the target window that should
receive the message. The target origin must match the origin of the sending window. If the target origin is not specified, it defaults to '*'.transferable
: This parameter controls whether the message should be transferred
between the two windows or if it should remain in the sending window. By
default, this parameter is set to false.To use PostMessage, you need to create a channel between the two scripts that want to communicate with each other. This can be done by invoking the postMessage
method on both sides and specifying the target script as an argument. The target script can then receive the message and process it according to its needs.
Here's an example of how you might use PostMessage:
// in sending window
window.postMessage({name: 'John', age: 30}, 'https://example.com');
// in target window
const message = event.data;
console.log(message); // Outputs { name: 'John', age: 30 }
In this example, the sending window is using PostMessage to send a message to the target window with the data {name: 'John', age: 30}
. The target window listens for the message using the event.data
property and logs it to the console.
One of the key restrictions of PostMessage is that it only works between windows that share the same origin. This means that if you want to send a message from one page hosted on one domain to another page hosted on a different domain, you will need to use a proxy server or some other mechanism to establish a shared origin between the two pages.
Another restriction of PostMessage is that it only works between windows, not between tabs. If you want to send a message between tabs within the same window, you can use the chrome.tabs
API instead.