--- title: Client.postMessage() slug: Web/API/Client/postMessage translation_of: Web/API/Client/postMessage ---
{{SeeCompatTable}}{{APIRef("Client")}}
{{domxref("Client")}} 接口的 Client.postMessage()
方法允许一个service worker客户端向一个 {{domxref("ServiceWorker")}}发送一个消息,会触发service worker的message事件,通过监听这个事件,可以获取这个消息。
Client.postMessage(message[, transfer]);
Void.
message
transfer {{optional_inline}}
从 service worker 向 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
});
}());
});
接收message:
navigator.serviceWorker.addEventListener('message', event => {
console.log(event.data.msg, event.data.url);
});
Specification | Status | Comment |
---|---|---|
{{SpecName('Service Workers', '#client-postmessage-method', 'postMessage()')}} | {{Spec2('Service Workers')}} | Initial definition. |