Clients.openWindow() - Web APIs 编辑

The openWindow() method of the Clients interface creates a new top level browsing context and loads a given URL. If the calling script doesn't have permission to show popups, openWindow() will throw an InvalidAccessError.

In Firefox, the method is allowed to show popups only when called as the result of a notification click event.

In Chrome for Android, the method may instead open the URL in an existing browsing context provided by a standalone web app previously added to the user's home screen. As of recently, this also works on Chrome for Windows.

Syntax

self.clients.openWindow(url).then(function(windowClient) {
  // Do something with your WindowClient
});

Parameters

url
A USVString representing the URL of the client you want to open in the window. Generally this value must be a URL from the same origin as the calling script.

Return value

A Promise that resolves to a WindowClient object if the URL is from the same origin as the service worker or a null value otherwise.

Examples

// Send notification to OS if applicable
if (self.Notification.permission === 'granted') {
  const notificationObject = {
    body: 'Click here to view your messages.',
    data: { url: self.location.origin + '/some/path' },
    // data: { url: 'http://example.com' },
  };
  self.registration.showNotification('You\'ve got messages!', notificationObject);
}

// Notification click event listener
self.addEventListener('notificationclick', e => {
  // Close the notification popout
  e.notification.close();
  // Get all the Window clients
  e.waitUntil(clients.matchAll({ type: 'window' }).then(clientsArr => {
    // If a Window tab matching the targeted URL already exists, focus that;
    const hadWindowToFocus = clientsArr.some(windowClient => windowClient.url === e.notification.data.url ? (windowClient.focus(), true) : false);
    // Otherwise, open a new tab to the applicable URL and focus it.
    if (!hadWindowToFocus) clients.openWindow(e.notification.data.url).then(windowClient => windowClient ? windowClient.focus() : null);
  }));
});

Specifications

SpecificationStatusComment
Service Workers
The definition of 'Clients: openWindow' in that specification.
Working DraftInitial definition.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:56 次

字数:3853

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文