I am getting notifications twice when the application in the background. Here is my Service-worker file. When we call this firebase.messaging() function, the service-worker starts receiving and displaying push notifications automatically. Service-worker is showing both notifications. one initializing by the firebase and one with this code self.registration.showNotification(notificationTitle, notificationOptions).
importScripts('https://www.gstatic.com/firebasejs/8.2.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.3/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in
firebase.initializeApp({
apiKey: "apiKey",
authDomain: "authDomain",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage( function(payload){
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: 'Testing',
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
How to prevent default notification?
Related
I am trying to implement Firebase Cloud FCM into my Vue 2 PWA app to get push notifications on background and foreground. I followed this tutorial: https://dev.to/vbanditv/how-to-add-fcm-firebase-cloud-messaging-to-vuejs-37np
If I use Firebase 8 and in firebase-messaging-sw.js I import these inks everything works:
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js')
,but the problem is that always it sends duplicates notifications
If I am trying to use firebase 9 and trying to importScripts with firebase 9 version, I am getting error like this:
https://dev.to/vbanditv/how-to-add-fcm-firebase-cloud-messaging-to-vuejs-37np#comment-1ld44
Can someone show me what I need to do to use Firebase 9 version at this case??
My firebase-messaging-sw.js at this moment looks like that:
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js')
const firebaseConfig = {
apiKey: apiKey,
authDomain: authDomainKEY,
projectId:projectIdKEY,
storageBucket: storageBucketKEY,
messagingSenderId: messagingSenderId
appId: appId
measurementId: measurementId
};
const app = firebase.initializeApp(firebaseConfig)
const isSupported = firebase.messaging.isSupported();
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
let currentTime = new Date();
lastReceivedTime = currentTime;
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body
};
self.registration.showNotification(notificationTitle,
notificationOptions);
}
});
MAYBE SOMEONE CAN SHOW ME BETTER TUTORIAL THAN THAT IN THE LINK??
I'm working on webapp where I have to update the Vuejs frontend with the notification message received through firebase console. Rightnow firebase-messaging-sw.js can be only place in public folder so that I'm not sure how to display the notifications or trigger some function inside vue app.
Im wondering how can i call some vue functions or update the UI
Sample firebase-messaging-sw.js code
/* eslint-disable */
importScripts("https://www.gstatic.com/firebasejs/8.0.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.0.1/firebase-messaging.js");
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: "value",
authDomain: "value",
databaseURL: "value",
projectId: "value",
storageBucket: "value",
messagingSenderId: "value",
appId: "value",
measurementId: "value",
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
// How to call some functions here or how to update this values to frontend
});
in firebase-messaging-sw.js
messaging.onBackgroundMessage((payload) => {
const channel = new BroadcastChannel('sw-messages');
channel.postMessage(payload);
});
in vue file:
mounted(){
const channel = new window.BroadcastChannel("sw-messages");
channel.addEventListener('message' (event)=> {
console.log(event)
})
}
BroadcastChannel Support
https://caniuse.com/?search=BroadcastChannel
I'm trying to get push notifications working with the Web version 9 JavaScript Firebase SDK in a Unity WebGL build. I got Firebase integrated and was successfully retrieving a token from Firebase when calling getToken(), but when I add the firebase-messaging-sw.js file, I start getting this error message:
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:52559/firebase-cloud-messaging-push-scope') with script ('http://localhost:52559/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
I've webpacked the firebase-messaging-sw.js (which the instructions in Firebase don't explicitly call out, but I'm assuming you have to do this to get it to work since I had to do the same thing for the rest of the firebase code and it's the whole point of version 9). I placed the webpacked firebase-messaging-sw.js file in the same folder as my index.html file.
Here's the firebase-messaging-sw.js file contents prior to packing:
import { getMessaging } from "firebase/messaging";
import { onBackgroundMessage } from "firebase/messaging/sw";
const firebaseConfig = {
apiKey: "XXXXXX",
authDomain: "XXXXXX",
databaseURL: "XXXXXX",
projectId: "XXXXXX",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXX",
appId: "XXXXXX",
measurementId: "XXXXXX"
};
firebase.initializeApp(firebaseConfig);
const messaging = getMessaging();
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I'm seeing the same results when I build and run locally and when I run it on a remote host. Has anyone got this to work or have any idea what I'm doing wrong?
I have set up the firebase.messaging().onMessage() and firebase-messaging-sw.js as per documentation.
In the index file,
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: 'XX',
authDomain: 'XX',
projectId: 'XX',
storageBucket: 'XX',
messagingSenderId: 'XX',
appId: '1:XX:XX',
measurementId: 'G-XXX',
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
console.log('have permission');
return messaging.getToken();
})
.then(function (token) {
console.log('have permission', token);
})
.catch(function (err) {
console.log('no permission', err);
});
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// Update the UI to include the received message.
navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
registration.showNotification(
payload.notification.title,
payload.notification
)
});
});
In the firebase-messaging-sw.js file:
importScripts('https://www.gstatic.com/firebasejs/8.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.5.0/firebase-messaging.js');
const firebaseConfig = {
apiKey: 'xx-xx',
authDomain: 'xx-xx.firebaseapp.com',
projectId: 'xx-assistant',
storageBucket: 'xx-xx.appspot.com',
messagingSenderId: 'xx',
appId: '1:xx:xxx',
measurementId: 'G-xx',
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log(
'[firebase-messaging-sw.js] Received background message ',
payload
);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
image: payload.notification.image,
click_action: payload.notification.click_action,
};
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
When I send a payload from the firebase console, I get the response in the front end and console.log outputs-
data: {notification: "{\"icon\":\"app.xxx.com\\/images\\/logo\",\"title\":\"New notification\",\"body\":\"Tthis is body\"}"}
from: "xxxxx"
But I don't see the notification pop that is generated by chrome.
As I understand, it should just show up if firebase.messaging().onMessage() or onBackgroundMessage is fired, but it is not.
What am I missing?
You need to implement the notification pop-up when you receive a notification in the foreground. It won't show up automatically.
Here's a code snippet from an answer showing how to do this:
messaging.onMessage(function(payload) {
console.log("onMessage: ", payload);
navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
registration.showNotification(
payload.notification.title,
payload.notification
)
});
});
My system-level permissions for notification were disabled.
After enabling the notification permissions, it worked without issue.
I am trying to setup FCM on my Nuxt app. I followed Firebase's web setup documentation. I set up a method on the default.vue file inside layouts folder to get current device token.
Here is the getDeviceToken() method on the default.vue file
mounted() {
this.getDeviceToken()
},
getDeviceToken() {
const messaging = firebase.messaging()
messaging
.requestPermission()
.then(() => {
console.log('Have permission')
return messaging.getToken()
})
.then((currentToken) => {
if (currentToken) {
console.log('Current Token : ', currentToken)
}
})
.catch((err) => {
console.log('Error occured', err)
})
messaging.onMessage(function(payload) {
console.log('onMessage: ', payload)
})
}
And here is my firebase-messaging-sw.js file
importScripts('https://www.gstatic.com/firebasejs/7.11.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.11.0/firebase-messaging.js')
const firebaseConfig = {
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxxx.firebaseapp.com',
databaseURL: 'xxxxxxxxxxxxxxxxxxxx.firebaseio.com',
projectId: 'xxxxxxxxxxxxxxxxx',
storageBucket: 'xxxxxxxxxxxxxxxxx.appspot.com',
messagingSenderId: 'xxxxxxxxxxx',
appId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxe65e18'
}
firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging()
After this setup, I was able to get the device token when app is running on foreground. But when I tried to send a message using Notification Composer or Postman, I have successful sent status but I am not receiving any notification on the browser. I am not sure why the onMessage method of FCM is not working. Any help would be much appreciated. Thanks