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.
Related
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
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
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
I am new in adding browser notification.How to use browser notification ? I couldn't figure out where to start. Can anyone provide me suggestion about how to start this.
Check Notification API for references
Code To request permission
document.addEventListener('DOMContentLoaded', function () {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
});
and for showing notifications
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'Icon Link',
body: "Notification Body",
});
notification.onclick = function () {
window.open("Href Here");
};
}
example
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== "denied") {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
notifyMe();
more info https://developer.mozilla.org/id/docs/Web/API/notification
For the browser notification to work your site or application should be served over https otherwise browsers wont allow it
mesg = {
title: "notification title",
body: "notification body",
icon: "location to an .ico image",
timer: true //for auto closing
}
// Let's check if the browser supports notifications
if (!('Notification' in window)) {
console.log('Browser does not support this feature.');
}else if (Notification.permission === 'granted') {
Notification.requireInteraction = false;
if (mesg.title !== 'undefined') {
const notification = new Notification(mesg.title, {
body: mesg.body,
icon: mesg.icon
});
if (mesg.timer) {
setTimeout(function () {
notification.close();
}, 5000);
}
return notification;
}// close if undefined
} else if (Notification.permission !== 'denied') {
alert('Please click Allow for enabling browser notifications');
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === 'granted') {
if (mesg.title !== 'undefined') {
const notification = new Notification(mesg.title, {
body: mesg.body,
icon: mesg.icon
});
if (mesg.timer) {
setTimeout(function () {
notification.close();
}, 5000);
}
return notification;
}// close if undefined
} else {
alert('Permission Denied :[');
}
});
}
I use this for my application, you can refactor it to remove duplicate code.
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
})
});
});