GCM pushEvent issue - push-notification

I have sent push notification to service-worker using GCM api. But in my service-worker has no attribute data. Hence, I am getting event.data as undefined.
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
console.log('testing');
var data = event.data;
var title = data.title;
var body = data.body;
var icon = '/images/image.png';
var tag = 'simple-push-demo-notification-tag';
event.waitUntil(function() {
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
});
});
In below code, I call GCM api.
uri = 'https://android.googleapis.com/gcm/send'
payload = json.dumps({
'registration_ids': [
User.objects.filter(id=user_id)[0].push_key
],
'data': json.dumps({'title':'New notification','message': 'new message'})
})
headers = {
'Content-Type': 'application/json',
'Authorization': 'key=<Project key>'
}
requests.post(uri, data=payload, headers=headers)

This looks like you've taken parts of the code, not all of it, and as a result, it's not working.
If you at the simple push demo repo, there is a function showNotification.
Here for Ref
function showNotification(title, body, icon, data) {
console.log('showNotification');
var notificationOptions = {
body: body,
icon: icon ? icon : '/images/touch/chrome-touch-icon-192x192.png',
tag: 'simple-push-demo-notification',
data: data
};
return self.registration.showNotification(title, notificationOptions);
}
There is where data is defined.
The data passed into this isn't from the event (or have anything to do with the event object).
To get your code running, just simplify it:
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
console.log('testing');
var title = 'My Title';
var body = 'My notification body';
var icon = '/images/image.png';
var tag = 'simple-push-demo-notification-tag';
event.waitUntil(function() {
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
});
});

Related

Firebase Service Worker

I have added actions to my firebase notifications, View and Opt-Out. I want users to be directed to the url which comes with the notification. The code below is supposed to work but it doesn't can someone please tell me what I am doing wrong.
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTopic = topic;
var notificationTitle = title;
var notificationOptions = {
body: body,
icon: icon,
image: image,
badge: badge,
click_action: url,
actions: [
{action: 'view', title: 'View'},
{action: 'unsubscribe', title: 'Opt-Out'}
]
}
self.registration.showNotification(notificationTitle, notificationOptions);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == url && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow(url);
}));
});
I had the same problem, in the of the day, I surrendered and just opened URL in a new tab. To pass URL I used at "data" object

web push notification - getting same notifications multiple times on chrome

I'm working on push notification. I'm facing the issue of getting same notification multiple time even I have written code for closing notification.
self.addEventListener('push', async (event) => {
if (event.data) {
const [data] = event.data.json()
const body = `Notification: ${data.timestampV} - ${data.eventType}`
const title = 'Web Notification'
const options = {
body,
icon: 'images/icon.png',
badge: 'images/badge.png',
}
event.waitUntil(self.registration.showNotification(title, options))
} else {
console.log('This push event has no data.')
}
})
self.addEventListener('notificationclick', function (event) {
event.notification.close()
// close all notifications
self.registration.getNotifications().then(function (notifications) {
notifications.forEach(function (notification) {
notification.close();
});
});
// eslint-disable-next-line no-undef
clients.openWindow('/feeds')
})
Thanks in advance.
This code works for me.
Add async function
var newEvent = new Event('push');
newEvent.waitUntil = e.waitUntil.bind(e);
newEvent.data = {
json: async function () {
var newData = e.data.json();
newData.notification = newData.data;
self.registration.showNotification(newData.data.title, {
...newData.data,
data: newData.data
});
return newData;
},
};
please check it from
https://github.com/firebase/quickstart-js/issues/71#issuecomment-396958853

How to use web push notifications with Meteor?

I am just hoping to find some good examples, but I haven't found anything. Pushjs is working on localhost, but how do I use the service worker correctly? I have linked the file, but this:
self.addEventListener('push', function (event) {
console.log('Received a push message', event);
// var notificationOptions = {
// body: 'The highlights of Google I/O 2015',
// icon: 'images/icon#192.png',
// tag: 'highlights-google-io-2015',
// data: null
// };
var notificationOptions = {
body: "Martin matches 89% with you!",
icon: '/images/LogoStore.jpg',
timeout: 4000,
link: "/",
onClick: function () {
window.focus();
this.close();
}
}
if (self.registration.showNotification) {
self.registration.showNotification('Timely News', notificationOptions);
return;
} else {
new Notification('Timely News', notificationOptions);
}
});
does not work.

Opera Push Notification - Unable to trigger notificationclick event

I am facing an issue with Opera Desktop Browser 47 when trying to send push notifications.
While the notifications are getting delivered correctly, I am unable to trigger the 'notificationclick' event. Nothing in the console as well.
Service Worker: (SW snippet with sample test data)
self.addEventListener('push', function(event) {
event.waitUntil(self.registration.pushManager.getSubscription().then(function(o) {
if (event.data) {
console.log(event.data);
var json=event.data.json();
var notifs = [];
const title = 'Sample Opera Title';
const options = {
body: 'Body of push notification',
};
payload_notifs.push(self.registration.showNotification(title, options));
return Promise.all(notifs);
}
}));
});
self.onnotificationclick = function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
};
Now, the thing is when I am putting a breakpoint just after sending the notification (Not letting the event complete), the notification is getting delivered, the 'notificationclick' event is also working.
This is actually very strange because things are working fine on other browsers with the same service code.
Does any one have an idea?
Try this:
self.addEventListener('push', function(event) {
event.waitUntil(self.registration.pushManager.getSubscription().then(function(o) {
if (event.data) {
console.log(event.data);
var json=event.data.json();
var notifs = [];
const title = 'Sample Opera Title';
const options = {
body: 'Body of push notification',
};
payload_notifs.push(self.registration.showNotification(title, options));
Promise.all(notifs);
}
}));
});
self.onnotificationclick = function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
};
Remove return, Opera is doing something weirdly.

Update dynamic data in service-worker.js

I have the below data coming in form of array from a url.
[{"title":"hey hi","body":"hello","url":"https://simple-push-demo.appspot.com/","tag":"new"}]
service-worker.js
it has the above url in fetch()
'use strict';
console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed new', event);
});
self.addEventListener('activate', function(event) {
console.log('Activatednew', event);
});
self.addEventListener('push', function(event) {
try{
console.log('Push message', event);
var ev = event;
//sample
return fetch("http://localhost/push-notifications-master/app/json.php").then(function(ev,response) {
response = JSON.parse(JSON.stringify(response));
return response;
}).then(function(ev,j) {
// Yay, `j` is a JavaScript object
console.log("j", j);
for(var i in j) {
var _title = j[i].title;
var _body = j[i].body;
var _tag = j[i].tag;
console.log("_body", _body);
}
ev.waitUntil(
self.registration.showNotification("push title", {
body: _body,
icon: 'images/icon.png',
tag: _tag
}));
});
return Promise.all(response);
}
catch(e){console.log("e", e)}
});
I am trying to see the above array data coming from that particular url in console.log("j",j);. but it shows undefined. How can i get dymanic data in sw.js Please Guide.
In your addEventListener('push' .... method, I think it might be better to wait for a response before parsing it.
Also, to be checked, but your php request should be in https (not checked by myself, but my request are on https).
Here how I do this :
event.waitUntil(
fetch('YOUR PHP URL').then(function(response) {
if (response.status !== 200) {
console.log('Problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification[0].title;
var body = data.notification[0].body;
var icon = data.notification[0].icon;
var notificationTag = data.notification[0].tag;
return self.registration.showNotification(title, {body: body,icon:icon, tag: notificationTag});
});
})
);
The json :
{"notification" : [{"title":"TITLE","body":"BODY","icon":"URL TO ICON","tag":"TAG"}]}
Hope it can be useful.

Resources