Firebase Cloud Messaging: Prevent background notifications in javascript client - javascript

I have a live score display website which is implemented with Google's channel API to push live score updates to the browser. Since Google is shutting down the channel API, I have to move to Firebase Cloud Messaging.
When I migrated to FCM, I had to add a service worker javascript file (firebase-messaging-sw.js). Whenever a score update is pushed to the browser, if the user is in another browser tab or the user has closed my web page tab, A notification appears to the user.
I don't need this notification and I want to disable it. Also, when user moves to another browser tab, I want to prevent the push message from going into the service worker and route it to my web page, so that when user returns to the tab again, the latest score is updated in the webpage.
Is there any way to achieve this?

You should pass a parameter (depends what you need to do) in the body of message like this:
$msg = [
'title' => pushTitle,
'body'=> pushBody,
'icon'=> icon.png,
'image'=> image.png,
'active'=> 1
];
The above is PHP but is also working in the same way-idea in any programming language. If you use Firebase then you should use cloud functions.
then in your js file:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Received background message', payload);
if(payload.data.active == 1){
return;
}
var notificationTitle = payload.data.title;
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
image: payload.data.image
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
If I had your code(what did you have done until now) I would gave you an exact answer.
If you have more questions don't hesitate to ask.

Related

Change color and icon of FCM notification in node.js

I am setting color and icon of my android notification in node.js after setting title and body it does not seem to work. and I need different notification background color and different icon for two notifications for same app that i am creating.
I have tried changing icon and color in android manifest meta tag and it works but the problem is i need separate notification icon and color for request received notification and separate notification color and icon for for new message notification. Also to mention that the code for both new request notification and new chat request notification and in same index.js file and after receiving new message, the notification that pops up is that of new friend request I don't know why.
//Request notification format.
return DeviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
from_sender_user_id : from_sender_user_id,
title: "New Friend Request",
body: `${senderUserName} wants to connect with you`,
icon: "/requestsmall.png"
color: "#fffbd7"
}
};
//New Message notification
return Token.then(result =>
{
const tid = result.val();
const pload =
{
notification:
{
from_sender_id : from_sender_id,
title: "New Message",
body: `${senderName} sent you a message`,
icon: "chatsmall.png"
color: "#e5fafa"
}
};
I want to display now different icon and color for these two notifications but it is not working also the send message notification displays the title and body of new request notification
As per my knowledge this is fully depend on the extension which you are using inside your project. Every extension of Firebase didn't support all features. Even if you send a FCM message directly from the Firebase console it will not redirect to the desired page. After many days I found an extension which supports all the features. just install and try inside your project and use it. Hope it will work for you.
For installation of the extension npm i cordova-plugin-firebasex

service worker notificationclick event doesn't focus or open my website in tab

I use FCM push notification in my website and I want user can come into my website when He or She clicks on the push notification. Please notes that The user may be in other app or in other browser tab and I want when the user gets fcm notification the user will be able to come into my website by a click on the notification in the Firefox browser. For this reason, I used notificationclick event which Is available in the service worker. The code that I used is this:
self.addEventListener('notificationclick', event => {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients
.matchAll({
type: 'window'
})
.then(clientList => {
for (let i = 0; i < clientList.length; i++) {
const client = clientList[i];
if (client.url === '/' && 'focus' in client) return client.focus();
}
if (clients.openWindow) return clients.openWindow('/');
})
);
});
It doesn't openwindow or focuses on my website tab. To debug the code I printed the clientList variable and It is an array with zero length.
The error that I get in the browser is this
On notification click:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable firebase-messaging-sw.js:92
The above error refers to this line of code:
event.waitUntil(
OS: Mac
firefox:63.0.3
reactjs:16.2.0
Move your notificationclick handler BEFORE your line of code with messaging = firebase.messaging();. The FCM JS SDK installs its own global notificationclick handler and its e.waitUntil() call manages to (somehow) break the Firefox event object. If you install your global handler first, then it gets called first and so it will actually work. However, it will probably break the FCM handler in some obscure fashion.
This is, IMO, a bug in Firefox itself with regards to Service Workers rather than FCM, but FCM certainly contributes to the problem.
Relevant:
https://github.com/firebase/quickstart-js/issues/282 (same FCM bug)
https://bugzilla.mozilla.org/show_bug.cgi?id=1468935 (same FCM + Firefox bug, bad fix)
https://bugzilla.mozilla.org/show_bug.cgi?id=1313096 (the Firefox dev team doesn't have a way to test the callback in its Service Worker test suite, which makes this part of Firefox ripe for bugs)
https://bugzilla.mozilla.org/show_bug.cgi?id=1489800 (same browser bug, different product)
If the goal is to open a specific URL when the notification is clicked, there may be an easier way. You can sent a "click_action" field in the FCM notification payload.
Your payload would look something like this:
"notification" : {
"body" : "Sample body",
"title" : "Sample title",
"click_action": "http://google.com"
}
And when the notification is clicked, it will open google.com in this example.

HTML5 Web Notification Permission Issue

I'm trying to implement HTML5 Notification API in my chat application. When I'm working on my localhost, everything works fine (The browser prompts me whether i need to allow notification from this site or not).
But when i try to access my application running in my local machine from some other machine which all connected in the same network. The browser is not prompting anything.
To Sum up my problem:
http://localhost:3000/home - This works!
http://10.1.0.126:3000/home - This doesn't works this way. (Even if try my from my computer or from other computer)
This is the code I'm using for notification api implementation
function createNotification(response){
if(!('Notification' in window)){
console.log("This browser does not Notification")
}else{
if(Notification.permission === 'granted'){
createNotification(response) // function to createNotification from response
}else if(Notification.permission !== 'denied'){
Notification.requestPermission((permission) => {
if(permission === 'granted'){
createNotification(response)
}
})
}
function createNotification(response){
// Construct the Notification
let title = response.sender_name
let notificationOptions = {
body: response.message,
icon: default_profile_pic
}
// Close the Notification after 3 seconds
let notification = new Notification(title, notificationOptions)
setTimeout(notification.close.bind(notification),3000)
}
P.S: I'm using ReactJS, Redux for my front-end development.
In Chrome 62 and newer you cannot request notification api at all unless the site is https:// secured. (see issue 779612) If you do have https on the site you should be able to use notifications and background push notifications.
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

How can I send push notification from javascript or c# to android - IOS and WinPhone

I implement push notification using this totarial. Now I want to send a notification from a website using server C# code or simply with a javascript code but the following link only implement sending notification using node:
var gcm = require('node-gcm');
var message = new gcm.Message();
//API Server Key
var sender = new gcm.Sender('AIzaSyCDx8v9R0fMsAsjoAffF-P3FCFWXlvwLhg');
var registrationIds = [];
// Value the payload data to send...
message.addData('message',"\u270C Peace, Love \u2764 and PhoneGap \u2706!");
message.addData('title','Push Notification Sample' );
message.addData('msgcnt','3'); // Shows up in the notification in the status bar
message.addData('soundname','beep.wav'); //Sound to play upon notification receipt - put in the www folder in app
//message.collapseKey = 'demo';
//message.delayWhileIdle = true; //Default is false
message.timeToLive = 3000;// Duration in seconds to hold in GCM and retry before timing out. Default 4 weeks (2,419,200 seconds) if not specified.
// At least one reg id required
registrationIds.push('APA91bwu-47V0L7xB55zoVd47zOJahUgBFFuxDiUBjLAUdpuWwEcLd3FvbcNTPKTSnDZwjN384qTyfWW2KAJJW7ArZ-QVPExnxWK91Pc-uTzFdFaJ3URK470WmTl5R1zL0Vloru1B-AfHO6QFFg47O4Cnv6yBOWEFcvZlHDBY8YaDc4UeKUe7ao');
/**
* Parameters: message-literal, registrationIds-array, No. of retries, callback-function
*/
sender.send(message, registrationIds, 4, function (result) {
console.log(result);
});
I want to send notification automatically using website or something like this (I want to scheduling sending notification in some times for remind drug time to patient).
In addition, I found this : pubnub for sending notification but unfortunately, it's not work correctly. Pubnub demo doesn't work.
How can I do this? Please help me.
Can you give either of these a try if you're writing C# on the server side? :)
Azure Notification Hub
PushSharp
Personally I'd write a Windows Service that runs a loop to poll the database for any notifications it needs to send out, sends it to Azure Notification Hub or AWS Push Notifications, sleeps for awhile, and then repeats the process.
You don't want to do it on the client side of a web page because the only way the code could ever run is if you had a web browser open all the time pointing to the page.

Why doesn't callback get called when the app is in background?

I'm developing a titanium app that needs to display a Banner Message under iOS when a push notification comes in. Therefore I used the following code to register on incoming push notifications:
var callbacks = {
types: [
Titanium.Network.NOTIFICATION_TYPE_BADGE,
Titanium.Network.NOTIFICATION_TYPE_SOUND,
Titanium.Network.NOTIFICATION_TYPE_ALERT
],
success:function(e){
console.log("success");
},
error:function(e){
console.log("error");
},
callback: function(e){
console.log("new push notification")
//code for displaying banner message would go here!
}
};
if(Ti.App.iOS.registerUserNotificationSettings){ //iOS 8 +
function onUserNotificationSettings(){
delete callbacks.types;
Ti.Network.registerForPushNotifications(callbacks);
Ti.App.iOS.removeEventListener("usernotificationsettings",onUserNotificationSettings);
}
Ti.App.iOS.addEventListener("usernotificationsettings",onUserNotificationSettings)
Ti.App.iOS.registerUserNotificationSettings(callbacks)
}else{ //up to iOS 7
Ti.Network.registerForPushNotifications(callbacks)
}
But the callback function does not get called when the app is in background. So, I also can't display the banner message there, since the code won't get executed.
What could be the reason why the callback does not get called when the app is in background? When it is in foreground, it works perfectly. Is it normal? If yes, where else would I put my code to display the banner message?
I'm using SDK version 3.4.0 on an iPhone 5 with iOS 8.1.1
Please note that sending the banner text through the apn-payload is not the solution. There are other usecases. For example, when the server needs to tell the client that there is new content to sync, where the user does not even need to get notified for. The client should just download the new content in background just when the notification arrives.
You need to register for the remote-notification background mode. This will wake up your app and give you execution time when you send the notifications.
For the record this is in the Appcelerator docs here
I've found out how to do it!
The callback will get called when the app is in background. All I had to do for it was to add the following to my tiapp.xml in ti:app/ios/plist/dict:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
After that, everything works fine!

Categories

Resources