Using channel messaging - Web APIs 编辑
The Channel Messaging API allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, or two documents via a SharedWorker
) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end.
In this article we'll explore the basics of using this technology.
Note:
This feature is available in Web Workers.Use cases
Channel messaging is mainly useful in cases where you've got a social site that embeds capabilities from other sites into its main interface via IFrames, such as games, address book, or an audio player with personalized music choices. When these act as standalone units, things are ok, but the difficulty comes when you want interaction between the main site and the IFrames, or the different IFrames. For example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into your main profile, or add new background music choices from the audio player onto the game? Such things are not so easy using conventional web technology, because of the security models the web uses. You have to think about whether the origins trust one another, and how the messages are passed.
Message channels on the other hand can provide a secure channel that allows you to pass data between different browsing contexts.
Note: For more information and ideas, the Ports as the basis of an object-capability model on the Web section of the spec is a useful read.
Simple examples
To get your started, we have published a couple of demos on Github. First up, check out our channel messaging basic demo (run it live too), which shows a really simple single message transfer between a page and an embedded <iframe>
.
Secondly, have a look at our multimessaging demo (run this live), which shows a slightly more complex setup that can send multiple messages between the main page and an IFrame.
We'll be focusing on the latter example in this article. It looks like so:
Creating the channel
In the main page of the demo, we have a simple form with a text input for entering messages to be sent to an <iframe>
. We also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>
.
var input = document.getElementById('message-input');
var output = document.getElementById('message-output');
var button = document.querySelector('button');
var iframe = document.querySelector('iframe');
var channel = new MessageChannel();
var port1 = channel.port1;
// Wait for the iframe to load
iframe.addEventListener("load", onLoad);
function onLoad() {
// Listen for button clicks
button.addEventListener('click', onClick);
// Listen for messages on port1
port1.onmessage = onMessage;
// Transfer port2 to the iframe
iframe.contentWindow.postMessage('init', '*', [channel.port2]);
}
// Post a message on port1 when the button is clicked
function onClick(e) {
e.preventDefault();
port1.postMessage(input.value);
}
// Handle messages received on port1
function onMessage(e) {
output.innerHTML = e.data;
input.value = '';
}
We start off by creating a new message channel by using the MessageChannel()
constructor.
When the IFrame has loaded, we register an onclick
handler for our button and an onmessage
handler for MessageChannel.port1
. Finally we transfer MessageChannel.port2
to the IFrame using the window.postMessage
method.
Let's explore how the iframe.contentWindow.postMessage
line works in a bit more detail. It takes three arguments:
- The message being sent. For this initial port transfering this message could be an empty string but in this example it is set to
'init'
. - The origin the message is to be sent to.
*
means "any origin". - An object, the ownership of which is transferred to the receiving browsing context. In this case, we are transferring
MessageChannel.port2
to the IFrame, so it can be used to communicate with the main page.
When our button is clicked, we prevent the form from submitting as normal and then send the value entered in our text input to the IFrame via the MessageChannel
.
Receiving the port and message in the IFrame
Over in the IFrame, we have the following JavaScript:
var list = document.querySelector('ul');
var port2;
// Listen for the initial port transfer message
window.addEventListener('message', initPort);
// Setup the transferred port
function initPort(e) {
port2 = e.ports[0];
port2.onmessage = onMessage;
}
// Handle messages received on port2
function onMessage(e) {
var listItem = document.createElement('li');
listItem.textContent = e.data;
list.appendChild(listItem);
port2.postMessage('Message received by IFrame: "' + e.data + '"');
}
When the initial message is received from the main page via the window.postMessage
method, we run the initPort
function. This saves the transferred port and register an onmessage handler that will be called each time a message is passed through our MessageChannel
.
When a message is received from the main page we create a list item and insert it in the unordered list, setting the textContent
of the list item equal to the event's data
attribute (this contains the actual message).
Next, we post a confirmation message back to the main page via the message channel by calling MessagePort.postMessage
on MessageChannel.port2
that was initially transferred to the IFrame.
Receiving the confirmation in the main page
Returning to the main page, let's now look at the onmessage handler function.
// Handle messages received on port1
function onMessage(e) {
output.innerHTML = e.data;
input.value = '';
}
When a message is received back from the IFrame confirming that the original message was received successfully, this outputs the confirmation to a paragraph and empties the text input ready for the next message to be sent.
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'Channel messaging' in that specification. | Living Standard |
Browser compatibility
MessageChannel
BCD tables only load in the browser
MessagePort
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论