I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.
Any ideas what I need to do to customize the message in the service worker?
Thank you very much!
For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71
short summary: do not include a "notification" element in your json message.
This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DB_URL',
projectId: 'YOUR_PROJ_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
tag: payload.data.tag,
data: payload.data.link,
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data));
});
JSON Message
{
"message": {
"token": "YOUR_TARGET_APP_TOKEN",
"data": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
"link": "https://yourapp.com/somewhere"
}
}
}
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.
The workaround I found for the web was to use the web browser native EH push to handle the event manually:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush
self.addEventListener('notificationclick', function(event) {
console.log('SW: Clicked notification', event)
let data = event.notification.data
event.notification.close()
self.clients.openWindow(event.notification.data.link)
})
self.addEventListener('push', event => {
let data = {}
if (event.data) {
data = event.data.json()
}
console.log('SW: Push received', data)
if (data.notification && data.notification.title) {
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: 'https://example.com/img/icons/icon-144x144.png',
data
})
} else {
console.log('SW: No notification payload, not showing notification')
}
})
When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.
Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).
If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.
Related
How to skip/open a specific screen based notification. Example: When a user clicks on the notification, the application should open and go directly to the notifications page instead of the home page.
when i was using react-native-push-notification i mannage to get the text of my notification this way :
componentWillMount() {
var _this = this;
PushNotification.configure({
onRegister: function(token) {
_this.props.InitToken(token.token);
},
onNotification: function(notification) {
setTimeout(() => {
if(!notification['foreground']){
_this.props.InitNotif(notification['message']);
}
}, 1);
PushNotification.localNotificationSchedule({
title: 'Notification with my name',
message: notification['name'], // (required)
date: new Date(Date.now()) // in 60 secs
});
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "YourID",
});
}
where
_this.props.InitToken(token.token);
and
_this.props.InitNotif(notification['message']);
are redux based function that update your state with the notification token and message. When you'r state is updated whith the notification message your can change route ou display the message on screen.
PS:
i dont know if it was the good way but i was working
componentWillMount() is depreciated.
I'm sending an FCM push notification from a Firebase backend to a Chrome Extension. I get it to show successfully in my Chrome Extension when it's in focus. I want it to show even if the Extension isn't in focus, but I can't get the service worker that's supposed to handle the notification even to fire.
I followed the Google tutorial to set up my JavaScript Chrome Extension client. I already tried this solution to not include a "notification" payload in my message, and this solution to register the worker manually (even though the tutorial doesn't say anything about either), but to no avail.
My service worker firebase-messaging-sw.js looks like this:
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
This is the POST request I use to send notifications (obviously with the correct SERVER_KEY and USER_TOKEN values):
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=<SERVER_KEY>
Cache-Control: no-cache
{
"data": {
"title": "Firebase",
"body": "Firebase is awesome",
"click_action": "http://localhost:5000/",
"icon": "http://localhost:5000/firebase-logo.png"
},
"to": "<USER_TOKEN>"
}
How do I get the service worker to receive the push notification and display it?
Thanks in advance :)
You can use Push API in service worker (firebase-messaging-sw.js):
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.2.2/firebase-messaging.js');
var config = {
...
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
this.onpush = event => {
console.dir(event.data.json());
// Here you can use event.data to compose Notification
// #see https://www.w3.org/TR/push-api/#pushmessagedata-interface
};
I have created firebase project for using Cloud Messaging . until now I have sent a message from backend to client successfully when the browser (chrome) is open but when I close the browser notification not sending until reopening of the browser in below code you can see my firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "My-Sender-Id"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
self.addEventListener('push', function(e) {
var data;
if (e.data) {
data = JSON.parse(e.data.text()).data;
} else {
data = {};
}
var title = data.title;
var options = {
body: data.body,
icon: 'assets/custom/img/logo.png',
vibrate: [100, 50, 100],
requireInteraction: true,
data: data.data ? data.data : null,
dir: "rtl",
actions: [{
action: data.action,
title: 'open',
icon: 'images/checkmark.png'
},
{
action: 'close',
title: 'close',
icon: 'images/xmark.png'
},
]
};
e.waitUntil(
self.registration.showNotification(title, options)
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
if (event.action != "" && event.action != "close") {
return clients.openWindow(event.action);
}
});
how can I have notification even browser is closed?
I believe you are using service worker for FCM, and the service worker only works when the browser is open ,as service worker is responsible for handling the push notification, when the browser is closed you won't receive any push notification, Actually the push notification will appear only when the browser is opened ,or the application for which you have configured FCM is open on chrome tabs but not focused, there is one work around or you say solution for it , that is make sure the chrome browser is active in the background even after closing chrome browser.
There is option in chrome settings
Goto Settings -> Advanced -> Continue running background apps when Google Chrome is closed make sure you enable it
i have tested the code of FCM , after enabling the option you will get the notification popup.
What you are trying to achieve should be accomplished using a database like firestore. When a notification is received at the time when browser is closed, in the service worker, you should add the code to save the notification message in the firestore so that when user opens the website again, you can retrieve the messages from the firestore and can display them to user. As soon as the browser is opened, any pending notification would be saved to the database by service worker.
I believe this should be the preferred way to achieve this.
I'm using the recently release FCM messaging support for push notifications on the chrome. When my app is in the background, I get the notification but nothing happens when I click the notification. How to I specify the URL which should open when the user clicks the notification? (I understand how its done using the pure service worker concept using the notificationclick event, I want to know how to do that using FCM messaging.)
messaging.setBackgroundMessageHandler(function(payload) {
var data = payload || {};
var shinyData = decoder.run(data);
console.log('[firebase-messaging-sw.js] Received background message ', shinyData);
return self.registration.showNotification(shinyData.title, {
body: shinyData.body,
icon: shinyData.icon
})
});
What am I missing here?
click_action is not one of the possible parameters of the showNotification function.
To handle the click on the notification, define a notificationclick event handler.
For example:
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(YOUR_URL_HERE));
});
Marco's answer is correct.
The Firebase Messaging Library is a wrapper on top of the Web Push API.
The notification: { click_action: 'https://...' } payload will show a notification and handle the click for you. To achieve the same with data payload you should implement the notificationclick event listener (Like Marco suggested).
self.addEventListener('notificationclick', function(event) {
event.notification.close();
... Do your stuff here.
});
You can also do the same with the notificationclose event:
self.addEventListener('notificationclose', function(event) {
... Do your stuff here.
});
I am using Ionic 2, and am trying to get Push Notifications working.
I have registered my app with Firebase, and can push notifications to it successfully.
I now need to set up, so that I can push notifications from my app. So I decided to use the following Cordova Plugin (cordova-plugin-fcm).
Question 1
When I follow it's instructions, by doing the following in my Ionic app:
app.ts
declare var FCMPlugin;
...
initializeApp() {
this.platform.ready().then(() => {
...
FCMPlugin.getToken(
function (token) {
....
I get the following Error at runtime:
EXCEPTION: Error: Uncaught (in promise): ReferenceError: FCMPlugin is
not defined
How do I solve this please?
Question 2
In order to send notifications from your app, the Cordova Plugin (cordova-plugin-fcm) instructs the following:
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
"notification":{
"title":"Notification title", //Any value
"body":"Notification body", //Any value
"sound":"default", //If you want notification sound
"click_action":"FCM_PLUGIN_ACTIVITY", //Must be present for Android
"icon":"fcm_push_icon" //White icon Android resource
},
"data":{
"param1":"value1", //Any data to be retrieved in the notification callback
"param2":"value2"
},
"to":"/topics/topicExample", //Topic or single device
"priority":"high", //If not set, notification won't be delivered on completely closed iOS app
"restricted_package_name":"" //Optional. Set for application filtering
}
This is not even Typescript or Javascript. So where does it go? I just don't understand. Any advise appreciated.
You should have FCMPlugin.js included in your HTML index file
find the path for js file into plugins directory of the app
Example : MyFCM\plugins\cordova-plugin-fcm\www\FCMPlugin.js
app.controller('AppCtrl', function(FCMPlugin,$scope,$cordovaToast,$cordovaDialogs,ionPlatform) {
// call to register automatically upon device ready
ionPlatform.ready.then(function (device) {
console.log('I am working');
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
$cordovaDialogs.alert(data.notification.body);
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
$cordovaDialogs.alert(data.notification.body);
//$cordovaToast.showShortCenter( JSON.stringify(data) );
}
},
function(msg){
$cordovaToast.showShortCenter('onNotification callback successfully registered: ' + msg);
},
function(err){
$cordovaToast.showShortCenter('Error registering onNotification callback: ' + err);
}
);
});
})