Firebase Service Worker - firebase

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

Related

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

OneSignal does not work on mobile

I have a problem getting "OneSignal" web push notifications to work on mobile-chrome browser, it works as expected on PC however, here is the code:
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "xxxxxxxxxx",
autoRegister: false,
notifyButton: {
enable: false,
},
});
});
</script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.on('subscriptionChange',function (isSubscribed) {
// if subscribed sends tags
if (isSubscribed) {
window.userPushed = true;
OneSignal.sendTag("table", "wasadds_22",function(tagsSent) {
console.log(tagsSent);
});
}
});
var isPushSupported = OneSignal.isPushNotificationsSupported();
if (isPushSupported) {
//if supported checks if enabled and shows propmpt if is not enabled
OneSignal.isPushNotificationsEnabled().then(function(isEabled) {
if (isEabled) {
console.log('push notifications are enabled');
window.userPushed = true;
}else{
swal({
title: 'Subscribe and get benefits!',
text: "Press allow ",
type: 'success',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Lets Do it!'
}).then((result) => {
if (result.value) {
// if user agrees the push prompt shows up
OneSignal.registerForPushNotifications();
OneSignal.setSubscription(true);
}
});
}
})
};
});
</script>
So the problem on mobile-chrome browser that it does not react in any way when I try to trigger push notification subscribe prompt it wouldn't show it, and no errros , also autoRegister does not work either , pls help

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.

GCM pushEvent issue

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
})
});
});

Resources