Client.postMessage() - Web APIs 编辑
The postMessage()
method of the Client
interface allows a service worker to send a message to a client (a Window
, Worker
, or SharedWorker
). The message is received in the "message
" event on navigator.serviceWorker
.
Syntax
client.postMessage(message[, transfer]); client.postMessage(message[, { transfer }]);
Parameters
message
- The message to send to the client. This can be any structured-clonable type.
transfer
Optional- A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.
Return value
undefined
.
Examples
Sending a message from a service worker to a client:
addEventListener('fetch', event => {
event.waitUntil(async function() {
// Exit early if we don't have access to the client.
// Eg, if it's cross-origin.
if (!event.clientId) return;
// Get the client.
const client = await clients.get(event.clientId);
// Exit early if we don't get the client.
// Eg, if it closed.
if (!client) return;
// Send a message to the client.
client.postMessage({
msg: "Hey I just got a fetch from you!",
url: event.request.url
});
}());
});
Receiving that message:
navigator.serviceWorker.addEventListener('message', event => {
console.log(event.data.msg, event.data.url);
});
Specifications
Specification | Status | Comment |
---|---|---|
Service Workers The definition of 'postMessage()' in that specification. | Working Draft | Initial definition. |
Browser compatibility
BCD tables only load in the browser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论