Search code examples
javascriptfirebasefirebase-cloud-messagingservice-workerfirebase-notifications

Filter web notifications by client-side


When I send a notification to some topic like...

const message = {
  data: { cost: 49 },
  topic: 'apple'
}
admin.messaging().send(message)

Question is about preventing/filtering notifications if user set something like >= 50 ? (Firestore/localStorage?)

How can I do that?

As I can think it should be filtered with messaging-sw.js but how and it's possible?

Or any better idea or I am missing something?


Solution

  • Case 1: When your app is in the foreground

    Case 2: When your app is in background

    • Save the user's data in IndexedDB, since users can access IndexedDB data in the service worker
    • You have to customize the function setBackgroundMessageHandler in the firebase-messaging-sw.js file as this guideline to handle the user's options
    • Note: If you set notification fields in your message payload, your setBackgroundMessageHandler callback is not called, and instead the SDK displays a notification based on your payload.

    Anyway, using a filter on the client-side is not a good approach, it should be done in server-side