Clients

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!
您也可以阅读此文章的English (US)版。

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

The Clients interface provides access to Client objects. Access it via self.clients within a service worker.

Methods

Clients.get()
Returns a Promise for a Client matching a given id.
Clients.matchAll()
Returns a Promise for an array of Client objects. An options argument allows you to control the types of clients returned. 
Clients.openWindow()
Opens a new browser window for a given url and returns a Promise for the new WindowClient.
Clients.claim()
Allows an active service worker to set itself as the controller for all clients within its scope

Examples

The following example shows an existing chat window or creates a new one when the user clicks a notification.

addEventListener('notificationclick', event => {
  event.waitUntil(async function() {
    const allClients = await clients.matchAll({
      includeUncontrolled: true
    });
    let chatClient;
    // Let's see if we already have a chat window open:
    for (const client of allClients) {
      const url = new URL(client.url);
      if (url.pathname == '/chat/') {
        // Excellent, let's use it!
        client.focus();
        chatClient = client;
        break;
      }
    }
    // If we didn't find an existing chat window,
    // open a new one:
    if (!chatClient) {
      chatClient = await clients.openWindow('/chat/');
    }
    // Message the client:
    chatClient.postMessage("New chat messages!");
  }());
});

Specifications

Specification Status Comment
Service Workers
The definition of 'Clients' in that specification.
Editor's Draft Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40 44.0 (44.0)[1] No support 27 No support
Feature Android Webview Chrome for Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support 40 40 44.0 (44.0) (Yes) No support 27 No support

[1] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

See also

文档标签和贡献者