Client.postMessage()

Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

Client 接口的 Client.postMessage() 方法允许一个service worker客户端向一个  ServiceWorker发送一个消息,会触发service worker的message事件,通过监听这个事件,可以获取这个消息。

语法

Client.postMessage(message[, transfer]);

返回

Void.

参数

message
发送给service worker的消息内容。
transfer 可选
可转移的对象,例如对端口的引用。

例子

从 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);
}); 

Specifications

Specification Status Comment
Service Workers
postMessage()
Working Draft Initial definition.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help! (en-US)
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 45.0[1] 44.0 (44.0)[2] 未实现 ? 未实现
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support 未实现 未实现 44.0 (44.0) ? 未实现 ? 未实现 45.0 [1]