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.
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 have mobile app which is developed in xamarin form. I am running webview on that for video call, now everything is working fine only i am not able to switch front or back camera during running video call.
Here is what i have tried so far but didnt succeed.
i have added select option in html code where i can choose front or back camera and here is the code of javascript
$('select').on('change', function (e) {
navigator.mediaDevices.enumerateDevices().then(function (devices) {
var valueSelected = $("#myselect option:selected").val();
alert(valueSelected);
//var myselect = 0;
if (valueSelected == "0") {
var cameras = [];
devices.forEach(function (device) {
'videoinput' === device.kind && cameras.push(device.deviceId);
});
var constraints = { video: { deviceId: { exact: cameras[0] } } };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { // Set your video displays
window.localStream = stream;
myapp.setMyVideo(window.localStream)
if (callback)
callback();
}, function (err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
else {
var cameras = [];
devices.forEach(function (device) {
'videoinput' === device.kind && cameras.push(device.deviceId);
});
var constraints = { video: { deviceId: { exact: cameras[1] } } };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { // Set your video displays
window.localStream = stream;
myapp.setMyVideo(window.localStream)
if (callback)
callback();
}, function (err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
//var myselect = $("#myselect option:selected").val();
});
});
when video call start by defaul it open back camera
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
#DavidWeldon I tried your code (Meteor observe changes added callback on server fires on all item) and it's very good thank you !
However I would like to have your advise : I use it for desktop notifications : when i get one notification, there is one console log (ok), but when i get another notification (total : 2), there are two console log (I want only one console log because there is only a +1 notification)
Here is my code :
if (Notification.permission !== "granted")
Notification.requestPermission();
var query = Notifications.find({userId: Meteor.userId(), read: false});
(function() {
var initializing = true;
query.observeChanges({
added: function(id, notification) {
if (!initializing) {
console.log(notification);
}
}
});
initializing = false;
})();
Thank you for your help ! :)
You could use another flag in there?
if (Notification.permission !== "granted")
Notification.requestPermission();
var query = Notifications.find({userId: Meteor.userId(), read: false});
(function() {
var initializing = true;
var firstNotif = true;
query.observeChanges({
added: function(id, notification) {
if (!initializing && firstNotif) {
firstNotif = false;
console.log(notification);
}
}
});
initializing = false;
})();
Finally I found an answer, exploring this post in discover meteor : https://www.discovermeteor.com/blog/template-level-subscriptions/
(in my question, I was working in Template.notifications.helpers)
Here's my new code :
Template.notifications.onCreated(function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
var instance = this;
instance.autorun(function () {
var query = Notifications.find({userId: Meteor.userId(), read: false});
query.observeChanges({
added: function(id, notification) {
var notification = new Notification('Notification', {
icon: '',
body: "You got a new notification !"
});
}
});
});
});