Skip to content

Instantly share code, notes, and snippets.

@oddmario
Last active June 29, 2023 13:00
Show Gist options
  • Save oddmario/c1bfb4d2c33a6a349b2f43e074e92a37 to your computer and use it in GitHub Desktop.
Save oddmario/c1bfb4d2c33a6a349b2f43e074e92a37 to your computer and use it in GitHub Desktop.
Send push notifications on your website using Firebase Cloud Messaging
const bodyparser = require("body-parser");
const express = require("express");
var admin = require("firebase-admin");
var serviceAccount = require("./serviceAccountFile.json");
// init
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
})
const app = express()
app.use(bodyparser.json())
const port = 3000
app.get('/send', (req, res) => {
// Note: Don't send both `notification` and `data` as this will result in sending the notification twice.
var message = {
webpush: {
notification: {
title: "Test push notification",
body: "Hi :)",
},
fcmOptions: {
link: 'https://google.com',
}
},
// topic: "appTopic",
token: "device token",
};
admin.messaging().send(message).then(response => {
res.status(200).send("Notification sent successfully");
})
.catch(error => {
console.log(error);
});
})
app.listen(port, () => {
console.log("Listening to port " + port)
})
// The compat versions of Firebase allow the usage of the old syntax `firebase.messaging()` instead of `getMessaging(app)`, etc. See https://stackoverflow.com/a/69184662/8524395
importScripts("https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging-compat.js");
firebase.initializeApp({
...
});
self.addEventListener('notificationclick', function(event) {
if ("click_action" in event.notification.data.FCM_MSG.notification) {} else {
return;
}
var action_click = event.notification.data.FCM_MSG.notification.click_action;
event.notification.close();
event.waitUntil(
clients.openWindow(action_click)
);
});
const messaging = firebase.messaging();
/*
We no longer need `onBackgroundMessage` as long as we're sending a `webpush` payload in our backend call. See https://stackoverflow.com/a/64903012/8524395
messaging.onBackgroundMessage(function(payload) {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload,
);
const notificationOptions = {
body: payload.data.body,
};
if( "icon" in payload.data ) {
notificationOptions['icon'] = payload.data.icon;
}
return self.registration.showNotification(payload.data.title, notificationOptions);
});
*/
<html>
<head>
<script>
const registerServiceWorker = async () => {
if ('serviceWorker' in navigator) {
try {
const registration = await navigator.serviceWorker.register(
'/firebase-messaging-sw.js', {
scope: '/',
}
);
if (registration.installing) {
console.log('Service worker installing');
} else if (registration.waiting) {
console.log('Service worker installed');
} else if (registration.active) {
console.log('Service worker active');
}
} catch (error) {
console.error(`Registration failed with ${error}`);
}
}
};
registerServiceWorker();
</script>
</head>
<body>
<script type="module">
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js";
import {
getAnalytics
} from "https://www.gstatic.com/firebasejs/9.23.0/firebase-analytics.js";
import {
getMessaging,
getToken,
onMessage
} from "https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging.js";
const firebaseConfig = {
... (the same used in the firebase-messaging-sw.js file)
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
getToken(messaging, {
vapidKey: 'The web push certificate public key pair here (obtain from Project settings -> Cloud messaging)'
}).then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
// Show permission request UI
console.log('No registration token available. Requesting permission...');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
onMessage(messaging, function(payload) {
console.log(
"[firebase-foreground] Received foreground message ",
payload,
);
var notificationOptions = {};
if ("body" in payload.notification) {
notificationOptions['body'] = payload.notification.body;
}
if ("icon" in payload.notification) {
notificationOptions['icon'] = payload.notification.icon;
}
if ("image" in payload.notification) {
notificationOptions['image'] = payload.notification.image;
}
var notif = new Notification(payload.notification.title, notificationOptions);
if ("fcmOptions" in payload) {
if ("link" in payload.fcmOptions) {
notif.onclick = function() {
window.open(payload.fcmOptions.link, '_blank').focus();
};
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment