相同选项卡的Clients.openWindow()等效项

时间:2019-02-23 23:44:42

标签: javascript

因此,当我收到浏览器通知时,有两种选择。如果客户没有打开网站,则打开一个新选项卡。但是,如何将客户发送到网站上已经存在的某个地方?

基本上,我想使用client.focus("some/highlevel/url")之类的东西,而不是clients.openWindow("https://someurl.com")

1 个答案:

答案 0 :(得分:0)

请使用此代码实现所需的行为:

// Attempt to extract notification URL
var url = event.notification.data.url;

// Check if it exists
if (url) {
    // Parse target URL
    var targetUrl = new URL(url);

    // Attempt to fetch open tabs
    event.waitUntil(clients.matchAll({ type: 'window' }).then(function (clientList) {
        // No match by default
        var matchFound = false;

        // Traverse clients list
        for (var client of clientList) {
            // Parse url
            var clientUrl = new URL(client.url);

            // Check host matches
            if (clientUrl.host === targetUrl.host && 'focus' in client) {
                // Update URL
                client.navigate(url);

                // Focus existing window
                client.focus();

                // Avoid opening a new window
                noMatch = true;
            }
        }

        // If no open tabs, or none match the host, open a new window
        if (!matchFound) {
            event.waitUntil(clients.openWindow(url));
        }
    }));