如何通过点击推送通知启动PWA(渐进式Web应用程序)?

jas*_*san 6 web-applications push-notification progressive-web-apps firebase-cloud-messaging

在这个例子之后,我看到PWA如何打开网址,但我如何使用推送通知来启动应用程序本身?不在浏览器中,而是全屏版本的PWA.

Mat*_*unt 7

这是Chrome中的一个怪癖.

如果用户在其清单中使用"独立"将Web应用程序添加到其主屏幕,则当用户单击Web应用程序图标时,它将在没有URL栏的情况下打开.

当收到推送消息并且打开相同的Web应用程序时,如果用户"最近"从主屏幕图标(当前在过去10天内)打开了Web应用程序,则不会显示URL栏.如果用户在该时间段内未使用主页图标,则会打开通知单击并显示URL栏.

有关详情,请参阅Chrome上的此问题:https://bugs.chromium.org/p/chromium/issues/detail?id = 541711

特别:

必须将Web应用程序添加到主屏幕,能够以独立模式打开,并且在过去十天内已从主屏幕打开.如果不满足任何这些条件,通知将回退到现有行为.

值得注意的是,PWA vs Browser本身并不是正确的思考方式.您总是在浏览器中启动,只是在不同的模式下,例如"独立"与"浏览器".

PWA(Progressive Web Apps)主要用于描述使用一组API来使用新的Web技术(即服务工作者,推送,Web应用程序清单等)提供良好的用户体验.


Kev*_*gia 6

摘自 Jake Archibald 的emojoy演示:

self.addEventListener('notificationclick', event => {
    const rootUrl = new URL('/', location).href;
    event.notification.close();
    // Enumerate windows, and call window.focus(), or open a new one.
    event.waitUntil(
      clients.matchAll().then(matchedClients => {
        for (let client of matchedClients) {
          if (client.url === rootUrl) {
            return client.focus();
          }
        }
        return clients.openWindow("/");
      })
    );
});
Run Code Online (Sandbox Code Playgroud)


小智 6

截至 2018 年 10 月

我设法使用 Chrome 69 使其正常工作。

在本例中,它是一个子应用程序(www.example.com/application)。

简而言之:仔细检查路径!

而且,每当我从推送通知启动应用程序时,我都会遇到未加载 cookie(登录信息)的问题,它打开正常,但未登录。如果您关闭它并点击先前添加在主屏幕上的应用程序图标,应用程序将启动已经登录。

我使用以下方法完成了它(见评论):

1) serviceworker.js

self.addEventListener('notificationclick', function (event)
{
    //For root applications: just change "'./'" to "'/'"
    //Very important having the last forward slash on "new URL('./', location)..."
    const rootUrl = new URL('./', location).href; 
    event.notification.close();
    event.waitUntil(
        clients.matchAll().then(matchedClients =>
        {
            for (let client of matchedClients)
            {
                if (client.url.indexOf(rootUrl) >= 0)
                {
                    return client.focus();
                }
            }

            return clients.openWindow(rootUrl).then(function (client) { client.focus(); });
        })
    );
});
Run Code Online (Sandbox Code Playgroud)

2)manifest.json

{
    "short_name": "AppNickName",
    "name": "ApplicationName",
    "icons": [
        {
            "src": "./icon.png",
            "sizes": "36x36",
            "type": "image/png",
            "density": 0.75
        }
    ],
    "start_url": "./",  //This matters
    "display": "standalone",  //This also matters
    "gcm_sender_id": "103953800507", //FCM always uses this number (April 2019)
    "background_color": "#c8c8c8",
    "theme_color": "#c8c8c8",
    "orientation": "any"
}
Run Code Online (Sandbox Code Playgroud)