postMessage() 方法在 Client interface allows a service worker to send a message to a client (a Window , Worker ,或 SharedWorker ). The message is received in the " message " event on navigator.serviceWorker .

句法

client.postMessage(message[, transfer]);
client.postMessage(message[, { transfer }]);
					

参数

message
The message to send to the client. This can be any structured-clonable type .
transfer 可选
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.

返回值

undefined .

范例

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

规范

规范 状态 注释
服务工作者
The definition of 'postMessage()' in that specification.
工作草案 初始定义。

浏览器兼容性

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. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
postMessage Chrome 45 Edge ≤79 Firefox 44 注意事项
44 注意事项
Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE 不支持 No Opera 32 Safari 不支持 No WebView Android 45 Chrome Android 45 Firefox Android 44 Opera Android 32 Safari iOS 不支持 No Samsung Internet Android 5.0

图例

完整支持

完整支持

不支持

不支持

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

见实现注意事项。

元数据

  • 最后修改:
  1. Client
  2. 特性
    1. frameType
    2. id
    3. type
    4. url
  3. 方法
    1. postMessage()