简体   繁体   中英

Android push notifications with 2 buttons for Progressive Web Apps?

I'm building an offline/installable Progressive Web App (PWA) with a Firebase Cloud Messaging (FCM) backend. Is it possible to generate an Android push notification with 2 buttons for an installed PWA? Here is an example: 在此处输入图片说明

Yes, this is possible over the new FCM REST API:

https://firebase.googleblog.com/2018/05/web-notifications-api-support-now.html

Payload Example:

    {
        "message": {
            "webpush": {
                "notification": {
                    "title": "Fish Photos 🐟",
                    "body":
                        "Thanks for signing up for Fish Photos! You now will receive fun daily photos of fish!",
                    "icon": "firebase-logo.png",
                    "image": "guppies.jpg",
                    "data": {
                        "notificationType": "fishPhoto",
                        "photoId": "123456"
                    },
                    "click_action": "https://example.com/fish_photos",
                    "actions": [
                        {
                            "title": "Like",
                            "action": "like",
                            "icon": "icons/heart.png"
                        },
                        {
                            "title": "Unsubscribe",
                            "action": "unsubscribe",
                            "icon": "icons/cross.png"
                        }
                    ]
                }
            },
            "token": "<APP_INSTANCE_REGISTRATION_TOKEN>"
        }
    }

Note that you will need to register callbacks for these custom actions in your service worker code, to handle whatever is supposed to happen when the user clicks on a custom button:

Service Worker:

    // Retrieve an instance of Firebase Messaging so that it can handle background messages.
    const messaging = firebase.messaging();

    // Add an event listener to handle notification clicks
    self.addEventListener('notificationclick', function(event) {
         if (event.action === 'like') {
                 // Like button was clicked

                 const photoId = event.notification.data.photoId;
                 like(photoId);
         }
         else if (event.action === 'unsubscribe') {
                 // Unsubscribe button was clicked

                 const notificationType = event.notification.data.notificationType;
                 unsubscribe(notificationType);
         }

         event.notification.close();
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM