Clients.openWindow()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

Clients接口的 openWindow() 方法创建一个顶级的浏览器上下文并加载给定的 URL. 如果调用脚本没有显示弹出窗口的权限, openWindow() 将抛出 InvalidAccessError.

在 Firefox 中,只有在作为通知点击事件的结果调用时,才允许该方法显示弹出窗口。

在 Chrome for Android 中,该方法可以改为在先前添加到用户主屏幕的 standalone web app 提供的现有浏览上下文中打开 URL.

语法

js
ServiceWorkerClients.openWindow(url).then(function (WindowClient) {
  // do something with your WindowClient
});

参数

url

一个 USVString,表示要在窗口中打开的 client 的 URL。通常,此值必须是与调用脚本有相同域的 URL.

返回值

如果 URL 来自与服务工作者相同的域,则 resolve 为 WindowClient 对象的 Promise,否则 resolve 为 null value.

示例

js
// When the user clicks a notification focus the window if it exists or open
// a new one otherwise.
onotificationclick = function (event) {
  var found = false;
  clients.matchAll().then(function (clientsArr) {
    for (i = 0; i < clientsArr.length; i++) {
      if (clientsArr[i].url === event.data.url) {
        // We already have a window to use, focus it.
        found = true;
        clientsArr[i].focus();
        break;
      }
    }
    if (!found) {
      // Create a new window.
      clients.openWindow(event.data.url).then(function (windowClient) {
        // do something with the windowClient.
      });
    }
  });
};

规范

Specification
Service Workers
# clients-openwindow

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
openWindow

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.