Показать сообщение отдельно
  #2 (permalink)  
Старый 04.08.2022, 12:32
Интересующийся
Отправить личное сообщение для krakoss Посмотреть профиль Найти все сообщения от krakoss
 
Регистрация: 22.03.2013
Сообщений: 25

код существующего ServiceWorker.js
var num = 1; //habr.com/ru/company/2gis/blog/350034/ ||  qna.habr.com/q/616168

self.addEventListener('install', () => self.skipWaiting())

self.addEventListener('activate', () => {
    self.clients.matchAll({ type: 'window' }).then(windowClients => {
        for (const windowClient of windowClients) {
            // Force open pages to refresh, so that they have a chance to load the
            // fresh navigation response from the local dev server.
            windowClient.navigate(windowClient.url)
        }
    })
})



self.addEventListener('push', function (event) {
    if (!event.data) return;

    var serverData = event.data.json();
    if (serverData) {
        var title = serverData.companynameandtown;
        var options = {
            tag: 'renotify',
            renotify: true,
            body: ++num > 1 ? serverData.textmessage : serverData.textmessage,
            icon: serverData.logocompany,
            data: {
                dateOfArrival: Date.now(),
                redirectUrl: serverData.redirectUrl
            }
        };
        event.waitUntil(
            // Получить список клиентов для SW
            self.clients.matchAll().then(function (clientList) {
                // Проверяем, есть ли хотя бы один сфокусированный клиент.
                var focused = clientList.some(function (client) {
                    return client.focused;
                });
                var notificationMessage;
                if (focused) {
                    notificationMessage = 'Imperio! You\'re still here, thanks!';
                } else if (clientList.length > 0) {
                    notificationMessage = 'Imperio! You haven\'t closed the page, ' +
                        'click here to focus it!';
                } else {
                    notificationMessage = 'Imperio! You have closed the page, ' +
                        'click here to re-open it!';
                }
                self.registration.showNotification(title, options);
            })
        );
    }
    else
        console.log("Нет данных для отображения.");
});

// Регистрируем обработчик события 'notificationclick'.
self.addEventListener('notificationclick', function (event) {
    event.notification.close();
    var url = event.notification.data.redirectUrl;
    event.waitUntil(
        // Получаем список клиентов SW.
        self.clients.matchAll().then(function (clientList) {
            // Если есть хотя бы один клиент, фокусируем его.
            if (clientList.length > 0) {
                return clientList[0].focus();
            }
            // В противном случае открываем новую страницу.
            return self.clients.openWindow(url);
        })
    );
});

self.addEventListener('notificationclose', function (event) {
    //do something
    event.notification.close();
});


function arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}
Ответить с цитированием