How can I initiate a PWA (progressive webapp) open from a click on a push notification?

前端 未结 4 1723
小蘑菇
小蘑菇 2021-02-04 09:56

Following this example, I see how PWA can open urls but how can I use push notification to launch the app itself? Not in the browser but the full screen version PWA.

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 10:26

    As of Oct/2018:

    I managed it to work using Chrome 69.

    In this example, it's a sub-application (www.example.com/application).

    In short: double check the paths!

    And also I had issues with not loaded cookies (login info) whenever I launched the app from a Push Notification, it opened fine, but not logged in. If you close it and tap the app icon previously added on homescreen, the app is launched already logged in.

    I accomplished it using the following (see comments):

    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(); });
            })
        );
    });
    

    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"
    }
    

提交回复
热议问题