2

the code below adds a listener to a firestore collection and sends a push notification when the web app is in the foreground. Is it possible to do the same in the background, perhaps, via service worker? I tried to import the firebase module to the service worker but I did not succeed

db.collection("favorites").onSnapshot(function(snapshot) {
        var response =snapshot.docChanges();
        response.forEach(function(change) {
                if (change.type === "added") {
                    var bodyPaint="New favorites: ";
                }
                if (change.type === "modified") {
                    var bodyPaint="Modified favorites: "; 
                }
                if (change.type === "removed") {
                    var bodyPaint="Removed favorites: ";
                }

            navigator.serviceWorker.ready.then(function(registration) {
                const title = 'LA BUENOS AIRES';
                const options = {
                  body: bodyPaint,
                  icon: 'images/icon.png',
                  badge: 'images/badge.png'
                };
                registration.showNotification(title, options);
              });
        });
});

1 Answer 1

3

A service worker cannot maintain a persistent connection to a server like that.

You can run a Cloud Function trigger that listens for the changes and when something needs a notification to the user, you can send a push notification.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the links Abraham, me imaginaba que tendría que hacerlo con firebase functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.