OneSignal does not work on mobile - push-notification

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

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

Get OneSignal UserID after subscribe

I'm using OneSignal to get notifications, so according to docs I made my SDK code like this:
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "myappID",
safari_web_id: "myID",
autoRegister: false,
promptOptions: {
/* My prompt options */
},
welcomeNotification: {
//my options
},
notifyButton: {
enable: true,
showCredit: false,
prenotify: true,
position: 'bottom-left',
text: {
/*My text options */
},
colors: { // My custom colors
}
}
}]);
OneSignal.push(function(){
OneSignal.showHttpPrompt();
OneSignal.getUserId().then(function(userId){
console.log("OneSignal User ID:", userId);
});
});
</script>
It works great showing slideshow prompt message, but after subscribe I need to refresh the website to get UserID in console. How can I modify this code function to get userID in console immediately after subscribe?
You need to add a listener for the subscription change event. Otherwise the getUserId call will trigger before the user has accepted the subscription. This is working for me:
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.on('subscriptionChange', function (isSubscribed) {
console.log("The user's subscription state is now:",isSubscribed);
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
console.log("OneSignal User ID:", userId);
});
});
});
});
OneSignal.push(["init", {
appId: "myappID",
safari_web_id: "myID",
autoRegister: false,
promptOptions: {
/* My prompt options */
},
welcomeNotification: {
//my options
},
notifyButton: {
enable: true,
showCredit: false,
prenotify: true,
position: 'bottom-left',
text: {
/*My text options */
},
colors: { // My custom colors
}
}
}]);

How to use browser notification

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.

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.

Resources