Нажмите кнопку уведомления ServiceWorker - Как я могу обновить sh страницу И перейти на ссылку привязки? - PullRequest
0 голосов
/ 21 января 2020

По сути, в моем событии «messagesclick» я пытаюсь открыть URL-адрес уведомлений. Он отлично работает для обычных URL. Но если URL-адрес имеет тег привязки (#), он просто попытается перейти к указанному привязке (который еще не существует).

Я могу легко вырезать часть привязки URL, и это работает для базовой страницы, затем она успешно обновит sh страницу, но не будет переходить к комментарию.

Итак, я попытался сделать это:

                if (cleanedClientUrl === cleanedUrl && 'focus' in client) {
                    //focus and reload the window that has this page open
                    client.focus();

                    //if the url had a # in it, first navigate to the cleaned url (otherwise it wont refresh)
                    if (url.indexOf('#'))
                        client.navigate(cleanedUrl);

                    client.navigate(url);

                    return;
                }

Какой я надеялся сначала перенаправить его на URL-адрес без cleanedUrl (без привязки), а затем перейти к исходному URL-адресу, включающему привязку, чтобы он спрыгнул вниз. Но, похоже, второй client.navigate отменяет первый.

Можно ли подождать, пока загрузится первая, или попросить страницу перезагрузиться, даже если в URL указан якорь?

Вот мой полный код:

//user clicked / tapped a push notification
self.addEventListener('notificationclick', function(event) {
    const clickedNotification = event.notification;
    clickedNotification.close();

    //exit if the url could not be found
    if (!event.notification.data || !event.notification.data.url) return;

    //get url from event
    var url = event.notification.data.url;
    //if the url contains a #, remove it and everything after it
    var cleanedUrl = url.indexOf('#') ? url.substring(0, url.indexOf('#')) :url;

    event.waitUntil(
        self.clients.matchAll({type: 'window', includeUncontrolled: true}).then( windowClients => {
            console.log('opening window', windowClients.length, 'windows')
            // Check if there is already a window/tab open with the target URL
            for (var i = 0; i < windowClients.length; i++) {
                var client = windowClients[i];

                //if the page url contains a #, remove it and everything after it
                var cleanedClientUrl;
                if (client.url.indexOf('#') !== -1)
                    cleanedClientUrl = client.url.substring(0, client.url.indexOf('#'));
                else cleanedClientUrl = client.url;

                // if the cleaned URLs match
                if (cleanedClientUrl === cleanedUrl && 'focus' in client) {
                    //focus and reload the window that has this page open
                    client.focus();

                    //if the url had a # in it, first navigate to the cleaned url (otherwise it wont refresh)
                    if (url.indexOf('#'))
                        client.navigate(cleanedUrl);

                    client.navigate(url);

                    return;
                }
            }
            // If not, then open the target URL in a new window/tab.
            if (self.clients.openWindow) {
                return self.clients.openWindow(url);
            }
        })
    );
});

1 Ответ

2 голосов
/ 21 января 2020

Не могли бы вы быстро перейти на якорь и сразу же перезагрузить страницу?

main JS thread

window.location = '#my-anchor-value';
window.location.reload();

ServiceWorker

если вам нужно объединить навигацию в SW, вам нужно дождаться завершения обещания первого navigate()

if (url.indexOf('#')) {
  return client.navigate(cleanedUrl)
  .then(() => client.navigate(url));
} else {
  return client.navigate(url);
}
...