Show push message in chrome - javascript

I want to show push notification using a service worker. In the developer tools -> Application -> Service workers I have the test text "a": "test message", I press the push and get the following error:
serviceWorker.js:48 Uncaught (in promise) TypeError: Failed to execute
'showNotification' on 'ServiceWorkerRegistration': No notification
permission has been granted for this origin.
How can I fix this? When you click on the push button, should the notification pop up?

For Push messages, you need two API's setup Notification API and Push API.
First things first, ask permission of the client for notification. Unless that is granted nothing works. So in your index.js/App.js place this snippet:-
function askForNPerm() {
Notification.requestPermission(function(result) {
console.log("User choice", result);
if (result !== "granted") {
console.log("No notification permission granted!");
} else {
configurePushSub();// Write your custom function that pushes your message
}
});
}
Once you are allowed with the permission, then call your Push function that has message to display.

It's Work. You also need to check if your browser has permission.
self.addEventListener('push', (event) => {
const options = {
body: 'This notification was generated from a push!',
icon: '',
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
actions: [
{
action: 'explore', title: 'Explore this new world',
icon: ''
},
{
action: 'close', title: 'Close',
icon: ''
},
]
};
event.waitUntil(
self.registration.showNotification('Title', options)
)
});

Related

PMA Service worker notification click isn't working

I am trying to show a notification and do something when it is clicked. The part that shows is working well, is receiving data from the server, however, the function of clicking on the notification does not work, I have done everything the documentation says, what I found on the web and here, everything points with the same functionality that I have implemented but it doesn't seem to work. I have made fictitious practices and as long as the data is not loaded from the server, the click is triggered, otherwise, with the data it does not.
Can anyone tell me what I am doing wrong? I'll really apreciate some help, I've two days with this.
self.addEventListener('push', (e) => {
let notification = e.data.json();
const title = 'My app ' + notification.title;
const options = {
body: notification.msg,
actions: [
{ action: 'yes', title: 'Aprobar' },
{ action: 'no', title: 'Rechazar' }
]
};
self.registration.showNotification(title, options);
}); //to show the notification with server info
self.addEventListener('notificationclick', function (event) {
console.log(event);
var noti = event.notification.data;
let r = event.notification.data.json();
console.log(noti); },
false); //handling the click
I've also tried with notificationclose to see if it catchs the click but it does not work either.
Important to note that it does not display any error or warning, it does simple do anything. Found the solution! See First Answer.
I found the solution! After playing around with the code and reading some others documents, it turns out that if my service on my server is a threading type, in my js has to be waiting for an answer. If someone needs it.
let notification = '';
self.addEventListener('push', (e) => {
notification = e.data.json();
const title = 'My app' + notification.title;
const options = {
body: notification.msg,
actions: [
{ action: 'yes', title: 'Aprobar' },
{ action: 'no', title: 'Rechazar' }
]
};
e.waitUntil(self.registration.showNotification(title, options)); }); //waitUntil to show the notification
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
let response = event.action;
event.waitUntil(
fetch(`api/authorizations/processor?uuid=${notification.uuid}&response=${response}&account=${notification.user}`,
{
method: 'GET',
mode: 'cors',
cache: 'default'
}).then((result) => {
if (!result.ok)
throw result;
return result.json();
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.log(errow);
})
); }); // waitUntil to expect a action

Paylod for ios silent push notification to update tab bar item badge using Firebase Cloud Function in JavaScript

I have all push notifications working fine.
But what is missing is the ability to handle silent push notifications when the app is in the background without the need for the user to tap on the notification when it appears to process the notification.
The following is the payload code from my deployed Firebase Cloud Function written in JavaScript but it doesn't work. The notification is displayed when app is in background but no delegate methods are called for the tab bar item badge to be updated.
I understand that in order to enable this I need to add the content-available flag to my payload.
I have enabled Background Fetch and Remote Notifications to my app and declared userNotificationCenter willPresent and userNotificationCenter didReceive delegate method.
const payload = {
notification: {
title: "I'm " + senderName,
body: notificationBody,
'content-available' : 1
},
data: {
SENDER_NAME: senderName,
SENDER_ID: fromId,
NOTIFICATION: 'invite'
}//end data
}//end payload
I found a solution to my question with the help of the question link as per the comments above. As this is an FCM function the the content_available should be specified in the options instead of the payload
const payload = {
notification: {
title: senderName + " sent you a message",
body: notificationBody
},
data: {
SENDER_NAME: senderName,
SENDER_ID: fromId,
NOTIFICATION: 'message'
}//end data
}//end payload
const options = {
content_available: true
}
//send message
return admin.messaging().sendToDevice(registrationTokens, payload, options).then( response => {

Chrome messaging - showing data instead of fixed message

I'm trying to make cloud messaging server, which sends notifications to chrome (PC and mobile).
I found https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/ and tutorial works.
In this tutorial there is a listener:
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelap';
const options = {
body: 'Yay it works.',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
And it works - when I send 'Hello world' through https://web-push-codelab.appspot.com/ it appears... but only in console.log.
How to change the options to get ${event.data.text()} intead of Yay it works?
I tried to change body: 'Yay it works.', into body: ${event.data.text()},
but Syntax Error: Unexpected token { appears.
The best what I did yesterday is go to sleep. Fresh mind and solution is comming immediately.
const options = {
body: event.data.text(),
icon: 'images/icon.png',
badge: 'images/badge.png'
};

Handle Push notification in Nativescript

I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});

GCM Android notification received on device but not displaying

GCM Cloud messaging notifications for my Ionic Android app are not appearing in my device's home screen, despite the notification registering in the app itself.
I'm using the npm module node-gcm to send push notifications.
var gcm = require('node-gcm');
var message = new gcm.Message({
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 10,
dryRun: false,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP."
}
});
var regIds = ['*device id*'];
var sender = new gcm.Sender('*api key*');
sender.send(message, { registrationIds: regIds }, function (err, result) {
if(err) console.error(err);
else console.log(result);
});
When I send a push notification to my device's ID, I get a successful response:
{ multicast_id: 8406385547051869000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1441962697347777%b67ee170f9fd7ecd' } ] }
I then get the following message in my Android Studio console:
V/GCMBroadcastReceiver﹕ onReceive: com.google.android.c2dm.intent.RECEIVE
V/GCMBroadcastReceiver﹕ GCM IntentService class: com.plugin.gcm.GCMIntentService
V/GCMBaseIntentService﹕ Acquiring wakelock
V/GCMBaseIntentService﹕ Intent service name: GCMIntentService-GCMIntentService-5
D/GCMIntentService﹕ onMessage - context: android.app.Application#2dc6dbff
V/GCMBaseIntentService﹕ Releasing wakelock
In the Google Play Developer Console GCM Debugger, my notifications also to appear to have been confirmed.
0: 1441899623073525% b67ee170f9fd7ecd Confirmed
Other than this I receive no error message in the Android Studio console when a notification has been received.
The Ionic app itself registers the notification once I've sent one. However when I'm out of the app. no notification is displayed in the home screen.
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
alert(notification);
if (ionic.Platform.isAndroid() && notification.event == "registered") {
window.localStorage['token'] = notification.regid;
var params = {
deviceType: 'android',
tokenId: notification.regid
};
NotificationService.registerDevice(params);
}
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge);
}
//notifications payload
if (notification.foreground == '0') {
if (notification.view) {
$timeout(function () {
$state.go('app.notifications');
});
} else {
if (notification.id) {
NotificationService.markNotificationAsRead(notification.id).success(function () {
$rootScope.$emit('notifications-read');
});
}
if (notification.chat) {
$timeout(function () {
$state.go('app.message', {id: notification.chat});
});
} else if (notification.post) {
$timeout(function () {
$state.go('app.singlePost', {id: notification.post});
});
} else if (notification.group) {
$timeout(function () {
$state.go('app.group', {id: notification.group});
});
}
}
}
});
You must add icon field in your notification block:
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP.",
icon: "#drawable/ic_launcher"
}
I was having the same issue, using the sample provided at the node-gcm page. After struggling for quite some time i came across this blogpost: http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
and modified my code according to the example provided in the blog post.
i guess there is an issue with "notification" object on node-gcm code, using message.addData seems to make it work,
in short replacing the message creation and sending logic as below worked for my application :
// For Android
if (row.device === "Android" && row.deviceToken) {
console.log(row.deviceToken);
var sender = new gcm.Sender(serverApiKey);
var message = new gcm.Message();
message.addData('title','İş Geliştirme Platformu');
message.addData('message','Yeni İleti');
message.addData('msgcnt','1');
//message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
var registrationIds = [];
registrationIds.push(row.deviceToken);
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
res.send(200,result);
});
}
add your server IP to white list and try again:
console.developers.google.com > APIs & auth > credential > select your server key > and add your server IP

Categories

Resources