Notes

Cloud Messaging

manifest.json

1
{
2
"gcm_sender_id": "103953800507"
3
}
Copied!

Request permission in browser

1
// index.html
2
const messaging = firebase.messaging();
3
messaging
4
.requestPermission()
5
.then(function() {
6
// Get Instance ID token. Initially this makes a network call, once retrieved
7
// subsequent calls to getToken will return from cache.
8
messaging.getToken()
9
.then(function(currentToken) {
10
if (currentToken) {
11
sendTokenToServer(currentToken);
12
updateUIForPushEnabled(currentToken);
13
} else {
14
// Show permission request.
15
console.log('No Instance ID token available. Request permission to generate one.');
16
// Show permission UI.
17
updateUIForPushPermissionRequired();
18
setTokenSentToServer(false);
19
}
20
})
21
.catch(function(err) {
22
console.log('An error occurred while retrieving token. ', err);
23
showToken('Error retrieving Instance ID token. ', err);
24
setTokenSentToServer(false);
25
});
26
}
27
.catch(function(err) {
28
console.log('Unable to get permission to notify.', err);
29
});
Copied!

Monitor token refresh

1
// index.html
2
// Callback fired if Instance ID token is updated.
3
messaging.onTokenRefresh(function() {
4
messaging
5
.getToken()
6
.then(function(refreshedToken) {
7
console.log('Token refreshed.');
8
// Indicate that the new Instance ID token has not yet been sent to the
9
// app server.
10
setTokenSentToServer(false);
11
// Send Instance ID token to app server.
12
sendTokenToServer(refreshedToken);
13
// ...
14
})
15
.catch(function(err) {
16
console.log('Unable to retrieve refreshed token ', err);
17
showToken('Unable to retrieve refreshed token ', err);
18
});
19
});
Copied!

Catch messages when page is in foreground

1
// index.html
2
// Handle incoming messages. Called when:
3
// - a message is received while the app has focus
4
// - the user clicks on an app notification created by a sevice worker
5
// `messaging.setBackgroundMessageHandler` handler.
6
messaging.onMessage(function(payload) {
7
console.log('Message received. ', payload);
8
// ...
9
});
Copied!

Create serviceWorker

You need a serviceWorker to listen for messages in the background
1
// firebase-messaging-sw.js
2
// Give the service worker access to Firebase Messaging.
3
// Note that you can only use Firebase Messaging here, other Firebase libraries
4
// are not available in the service worker.
5
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
6
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
7
8
// Initialize the Firebase app in the service worker by passing in the
9
// messagingSenderId.
10
firebase.initializeApp({
11
messagingSenderId: 'YOUR-SENDER-ID',
12
});
13
14
// Retrieve an instance of Firebase Messaging so that it can handle background
15
// messages.
16
const messaging = firebase.messaging();
Copied!

Send message to single recipient

1
// Cloud Function
2
// This registration token comes from the client FCM SDKs.
3
var registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';
4
5
// See the "Defining the message payload" section below for details
6
// on how to define a message payload.
7
var payload = {
8
notification: {
9
title: 'Title of your push notification',
10
body: 'Body of your push notification',
11
click_action: 'https://dummypage.com',
12
},
13
data: {
14
score: '850',
15
time: '2:45',
16
},
17
};
18
19
// Send a message to the device corresponding to the provided
20
// registration token.
21
admin
22
.messaging()
23
.sendToDevice(registrationToken, payload)
24
.then(function(response) {
25
// See the MessagingDevicesResponse reference documentation for
26
// the contents of response.
27
console.log('Successfully sent message:', response);
28
})
29
.catch(function(error) {
30
console.log('Error sending message:', error);
31
});
Copied!

Send multi-cast message

1
// Cloud Function
2
// These registration tokens come from the client FCM SDKs.
3
var registrationTokens = [
4
'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
5
// ...
6
'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...',
7
];
8
9
//...
10
admin
11
.messaging()
12
.sendToDevice(registrationTokens, payload)
13
.then(function(response) {
14
//...
15
});
Copied!

Send device-group message

1
// Cloud Function
2
var notificationKey = 'some-notification-key';
3
4
//...
5
admin
6
.messaging()
7
.sendToDeviceGroup(notificationKey, payload)
8
.then(function(response) {
9
// ...
10
});
Copied!

Send topic message

1
// Cloud Function
2
// The topic name can be optionally prefixed with "/topics/".
3
var topic = 'highScores';
4
5
//...
6
7
admin
8
.messaging()
9
.sendToTopic(topic, payload)
10
.then(function(response) {
11
//...
12
});
Copied!

Send to condition

Conditions support only two operations per expression
1
// Cloud Function
2
// Define a condition which will send to devices which are subscribed
3
// to either the Google stock or the tech industry topics.
4
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
5
6
//...
7
admin
8
.messaging()
9
.sendToCondition(condition, payload)
10
.then(function(response) {
11
//...
12
});
Copied!

Message options

1
// Cloud Function
2
var registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';
3
4
var payload = {
5
notification: {
6
title: 'Urgent action needed!',
7
body: 'Urgent action is needed to prevent your account from being disabled!',
8
},
9
};
10
11
// Set the message as high priority and have it expire after 24 hours.
12
var options = {
13
priority: 'high',
14
timeToLive: 60 * 60 * 24,
15
};
16
17
admin
18
.messaging()
19
.sendToDevice(registrationToken, payload, options)
20
.then(function(response) {
21
//...
22
});
Copied!

Subscribe to topic

1
// Cloud Function
2
var registrationTokens = [
3
'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
4
// ...
5
'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...',
6
];
7
8
admin
9
.messaging()
10
.subscribeToTopic(registrationTokens, topic)
11
.then(function(response) {
12
//...
13
});
Copied!

Subscribe to topic

1
// Cloud Function
2
const registrationTokens = [
3
'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
4
// ...
5
'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...',
6
];
7
8
const topic = 'highScores';
9
10
admin
11
.messaging()
12
.subscribeToTopic(registrationTokens, topic)
13
.then(function(response) {
14
//...
15
});
Copied!

Unsubscribe to topic

1
// Cloud Function
2
const registrationTokens = [
3
'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
4
// ...
5
'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...',
6
];
7
8
const topic = 'highScores';
9
10
admin
11
.messaging()
12
.unsubscribeFromTopic(registrationTokens, topic)
13
.then(function(response) {
14
//...
15
});
Copied!
Last modified 3yr ago