Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Setting up push notifications with Firebase Cloud Messaging. #238

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions frontend/public/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* eslint-disable */

// https://github.com/firebase/quickstart-js/blob/master/messaging/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-app-compat.js')
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-messaging-compat.js')

const firebaseConfig = {
apiKey: 'AIzaSyCfjxatTVD8kWt_1hHAFDgrOGgXjNw1ZC0',
authDomain: 'sds-butterfly.firebaseapp.com',
databaseURL: 'https://sds-butterfly-default-rtdb.firebaseio.com',
projectId: 'sds-butterfly',
storageBucket: 'sds-butterfly.appspot.com',
messagingSenderId: '265457992927',
appId: '1:265457992927:web:f8b8781a13dd1e4b3fd56a',
}
firebase.initializeApp(firebaseConfig)

const messaging = firebase.messaging()

// https://firebase.google.com/docs/cloud-messaging/js/receive
messaging.onBackgroundMessage(function (payload) {
console.log(payload)
// https://stackoverflow.com/a/48900941
self.addEventListener('push', function (event) {
console.log('Received a push message', event)

var title = 'Yay a message.'
var body = 'We have received a push message.'
var icon = 'YOUR_ICON'
var tag = 'simple-push-demo-notification-tag'
var data = {
doge: {
wow: 'such amaze notification data',
},
}

event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag,
data: data,
})
)
})
})
3 changes: 2 additions & 1 deletion frontend/public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
"sizes": "128x128",
"purpose": "any maskable"
}
]
],
"gcm_sender_id": "103953800507"
}
60 changes: 58 additions & 2 deletions frontend/src/pages/StatusPage.jsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,80 @@
import React from 'react'
/* global Notification */
/* global prompt */

import React, { useContext } from 'react'
import { Link } from 'react-router-dom'
import { useBackendFetchJson } from '../app/utils'
import { getMessaging, getToken, onMessage } from 'firebase/messaging'
import { faBell } from '@fortawesome/free-solid-svg-icons'

import { FirebaseAppContext, useBackendFetchJson } from '../app/utils'
import { Button } from '../app/ui'

const DEFAULT_STATUS = 'Contacting backend API...'
const VAPID_KEY =
'BIUHqTsoPcfaNSwYTav69J-Mt_QUQgkiJZG4Klg_Qej000U1550cJVFo3ovKhxWRIm70u6_FQTSGbhlZF7uDCSI'

function getStatusMessage(res, error) {
if (error) return `Error: ${error}`
if (res) return JSON.stringify(res, null, 4)
return DEFAULT_STATUS
}

async function authorizeNotifications(messaging) {
try {
const permission = await Notification.requestPermission()
if (permission !== 'granted') {
// eslint-disable-next-line no-console
console.log('Permission not granted:')
// eslint-disable-next-line no-console
console.log(permission)
return [null, null]
}
const token = await getToken(messaging, { vapidKey: VAPID_KEY })
if (!token) {
// eslint-disable-next-line no-console
console.log('No token. Request permission to generate one.')
return [null, null]
}
return [token, null]
} catch (error) {
// eslint-disable-next-line no-console
console.log('Error while requesting permission for notifications:')
// eslint-disable-next-line no-console
console.error(error)
return [null, error]
}
}

export default function StatusPage() {
const [res, error] = useBackendFetchJson({ route: '/' })
const statusText = getStatusMessage(res, error)
const app = useContext(FirebaseAppContext)
const messaging = getMessaging(app)
const doTestNotification = async () => {
const [token, notifErr] = await authorizeNotifications(messaging)
if (notifErr) return
// eslint-disable-next-line no-console
console.log(token)
// eslint-disable-next-line no-alert
prompt('Token:', token)
}
onMessage(messaging, (payload) => {
// eslint-disable-next-line no-console
console.log(payload)
})
return (
<div className="Layout Page">
<div>
<h1 className="BigTitle">Status</h1>
<Link to="/">Back to Home</Link>
<h2>Backend API</h2>
<pre>{statusText}</pre>
<h2>Push Notifications</h2>
<Button
label="Send Test Notification"
iconBefore={faBell}
onClick={doTestNotification}
/>
</div>
</div>
)
Expand Down