Skip to content

Instantly share code, notes, and snippets.

@zmts
Last active December 2, 2022 12:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zmts/88e5b475e4ceb917cb01a3764702c127 to your computer and use it in GitHub Desktop.
Save zmts/88e5b475e4ceb917cb01a3764702c127 to your computer and use it in GitHub Desktop.
Firebase web push notification
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-messaging.js')
firebase.initializeApp({
apiKey: "---",
authDomain: "test.firebaseapp.com",
databaseURL: "https://test.firebaseio.com",
projectId: "test",
storageBucket: "test.appspot.com",
messagingSenderId: "11111111111",
appId: "1:1111111111:web:ba1jh33j13h12h3j21h"
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
const data = JSON.parse(payload.data.notification)
console.log('data', data)
return self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon || '/firebase-logo.png'
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Firebase notification</title>
</head>
<body>
<!-- firebase notifications begin -->
<!-- firebase notifications begin -->
<!-- firebase notifications begin -->
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-messaging.js"></script>
<script>
firebase.initializeApp({
apiKey: "---",
authDomain: "test.firebaseapp.com",
databaseURL: "https://test.firebaseio.com",
projectId: "test",
storageBucket: "test.appspot.com",
messagingSenderId: "11111111111",
appId: "1:1111111111:web:ba1jh33j13h12h3j21h"
})
const messaging = firebase.messaging();
messaging.requestPermission()
.then(() => {
return messaging.getToken().then((currentToken) => {
if (currentToken) {
console.log('currentToken:', currentToken)
// TODO send token to api
return currentToken
}
})
}).catch(error => {
console.log(error)
})
messaging.onTokenRefresh(() => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed:', refreshedToken);
// TODO send refreshed token to api
}).catch((err) => {
console.log(err);
});
});
</script>
<!-- firebase notifications end -->
<!-- firebase notifications end -->
<!-- firebase notifications end -->
<div id="app"></div>
</body>
</html>
POST: https://fcm.googleapis.com/fcm/send

Headers:
Content-Type: application/json
Authorization: key=AAAALc68Sz8:APA...

Body:
{
	"to": "dH34nQFfLats1Nt4z9rHLT:APA91bEt...",
	"data": {
		"notification": {
			"title": "Hello title",
			"body": "Boomm!!!!",
			"icon": "https://i.imgur.com/lol.png",
			"link": "https://gist.github.com/zmts"
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment