Skip to content

Instantly share code, notes, and snippets.

@birchb
Forked from yusufkandemir/README.md
Created June 24, 2020 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save birchb/1da2f628da07c27b98505a6bf3e49602 to your computer and use it in GitHub Desktop.
Save birchb/1da2f628da07c27b98505a6bf3e49602 to your computer and use it in GitHub Desktop.
Quasar + FCM(Firebase Cloud Messaging) Setup

What to do next?

Manage The Subscription State

Manage the subscription state using localStorage, IndexedDB, or a server-side solution(e.g. in Firestore, store per-user), depending on the flow of your app.

Notification UI/UX

Create a notification section in settings, in navbar or just prompt it directly(not recommended, bad UX). On UI interaction such as a subscribe button, call subscribeNotifications with the related parameters(subscribe = true/false, token), then persist the notification state.

Create Notifications

You can create and manage the notifications from Firebase Console. You can also create some cloud functions to create them manually or on some action(maybe when a new post inserted to firestore).

// /functions/index.js
const functions = require('firebase-functions')
const subscribeNotifications = require('./subscribeNotifications')
exports.subscribeNotifications = functions.https.onCall(subscribeNotifications)
// /functions/subscribeNotifications.js
const {
messaging,
HttpsError,
} = require('./admin')
// data: { token: string, subscribe: bool }
module.exports = async (data, context) => {
// Validate the data
try {
if (data.subscribe) {
const response = await messaging.subscribeToTopic(data.token, 'brochures')
console.log('User subscription successful', { token: data.token, response })
} else {
const response = await messaging.unsubscribeFromTopic(data.token, 'brochures')
console.log('User unsubscription successful', { token: data.token, response })
}
} catch (error) {
console.error(`User ${data.subscribe ? '' : 'un'}subscription failed`, error)
throw new HttpsError('internal', 'Something went wrong :(')
}
}
// /public/firebase-messaging-sw.js
/* eslint-env serviceworker */
/* global firebase */
importScripts('https://www.gstatic.com/firebasejs/7.7.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.7.0/firebase-messaging.js')
firebase.initializeApp({
projectId: PROJECT_ID_HERE,
apiKey: API_KEY_HERE,
messagingSenderId: MESSAGING_SENDER_ID_HERE,
appId: APP_ID_HERE
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(async payload => {
return self.registration.showNotification(payload.title, payload)
})
// /src/boot/firebase.js
import firebase from 'firebase/app'
import 'firebase/functions'
import 'firebase/messaging'
import { LocalStorage, Notify } from 'quasar'
export default ({ /* */ }) => {
firebase.initializeApp(FIREBASE_CREDENTIALS_HERE)
const messaging = firebase.messaging()
messaging.usePublicVapidKey(YOUR_PUBLIC_VAPID_KEY_HERE)
messaging.onTokenRefresh(async () => {
// Store the subscription state in localStorage, database, etc.
// Then check if the user is subscribed to notifications
if (LocalStorage.getItem('fcm.isSubscribed') !== true) return
// Token is refreshed, let the server know
const subscribeNotifications = firebase.functions().httpsCallable('subscribeNotifications')
const token = await messaging.getToken()
await subscribeNotifications({ token, subscribe: true })
})
messaging.onMessage(payload => {
console.log('Message received.', payload)
const notification = payload.notification
Notify.create({
message: `${notification.title} - ${notification.body}`
// You can also handle actions here, they are in `notification.actions`
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment