When app in background, firebase plugin not calling onMassageReceived and I can't add vibration, when notification received. How I can solve that?
import firebase = require("nativescript-plugin-firebase");
var vibrator = require("nativescript-vibrate");
firebase.init({
url: AppUrl
}).then(
(instance) => {
console.log("firebase.init done true");
},
(error) => {
console.log("firebase.init error: " + error);
}
);
firebase.addOnMessageReceivedCallback((message:any)=>{
vibrator.vibration(500);
});
Related
I am using firebase version 8.2.7
Code in public/firebase-messaging-sw.js
//firebase-messaging-sw.js
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 = {
// firebase config credentials
};
const app = firebase.initializeApp(firebaseConfig);
const messaging = app.messaging();
messaging.onBackgroundMessage((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);
});
Code in firebase.js
//firebase.js
import firebase from "firebase/app";
import "firebase/firebase-messaging";
const firebaseConfig = {
// firebase config credentials
};
firebase.initializeApp(firebaseConfig);
export default firebase.messaging();
Code in main.js
import firebaseMessaging from "./firebase"; // firebase
firebaseMessaging.getToken({
vapidKey: process.env.VUE_FIREBASE_PUSH_KEY })
.then((currentToken) => {
if (currentToken) {
console.log("Firebase Current Token", currentToken);
// this.$messaging.onMessage((msg) => {
// window.alert(msg);
// });
// // getMessaging(payload => {
// // console.log("//////////////message Firebase", payload);
// // window.alert(payload);
// // });
} else {
console.log("No registration token available. Request permission to generate one.");
}}).catch( err => {
console.log("/////////errrr Firebase", err);
});
Vue.prototype.$messaging = firebaseMessaging;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
randomComponent.js
methods: {
getFirebaseNotifications() {
try {
this.$messaging.onMessage((payload) => {
console.log("//////////////message Firebase", payload);
});
} catch (error) {
console.log("/////////errrr Firebase", error);
}
},
}
created() {
this.getFirebaseNotifications();
}
What changes should I make in public/firebase-messaging-sw.js to receive the push notifications from Firebase Cloud Messaging (FCM) whenever they are created and how can I register such a service worker in my vue app. Also, how can I receive the FCM notifications in my vue components ?
I am trying to send notification in react native via rest api. In response i'm getting success :1. The problem here is i'm not getting notification in emulator.
const token = await firebase.messaging().getToken();
console.log("token in sendNotification ",token)
const FIREBASE_API_KEY = "firebaseApiKey";
const message = {
to :token,
notification: {
title: "This is a Notification",
boby: "This is the body of the Notification",
vibrate: 1,
sound: 1,
show_in_foreground: true,
priority: "high",
content_available: true,
}
}
let headers = new Headers({
"Content-Type" : "application/json",
Authorization: "key=" + FIREBASE_API_KEY,
})
try {
let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
method: "POST",
headers,
body: JSON.stringify(message),
})
response = await response.json();
console.log("response ", response);
} catch (error) {
console.log("error ", error);
}
https://firebase.google.com/docs/cloud-messaging/js/receive
You can follow the incoming message documentation
// Handle incoming messages. Called when:
// - a message is received while the app has a focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
In useEffect of App.js
import React,{useEffect} from 'react'
import{View,Text} from 'react-native';
async function onDisplayNotification() {
// Create a channel
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
// Display a notification
await notifee.displayNotification({
title: 'Notification Title',
body: 'Main body content of the notification',
android: {
channelId,
smallIcon: 'ic_launcher', // optional, defaults to 'ic_launcher'.
},
});
}
const App=()=> {
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onMessage((payload) => {
console.log('Message received. ', payload);
onDisplayNotification();
// ...
});
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
alert("Notification");
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
}, []);
return (
<View>
</View>
)
}
export default App;
I am trying to send notifications from firebase console to my react-native app
I followed the poor documentation here as much as I understand: https://invertase.io/oss/react-native-firebase/v6/messaging/quick-start
I installed #react-native-firebase/app and /messaging and here is my code in component:
componentDidMount() {
this.reqNotifications()
this.checkNotificationPermission()
}
reqNotifications() {
requestNotifications(['alert', 'badge', 'sound']).then(({status, settings}) => {
console.log('NOTIFICATION STATUS' + status)
});
}
async checkNotificationPermission() {
const enabled = await messaging().hasPermission();
if (enabled) {
console.log('APPROVED');
await messaging().registerForRemoteNotifications()
messaging().getToken().then(token => console.log('token: >> ' + token))
} else {
console.log('NOT APPROVED');
}
}
I am requesting permission via react-native-permissions and permission request is
working.
My Apple APNs are OK on Apple and Firebase console
And I am getting my token by getToken() method on the code
succesfully.
But I cant send anything to device from firebase; nothing happening on neither foreground nor background . I tried with-token test and also tried normal but no, nothing happens.
I added this code to componentDidMount:
messaging().onMessage(async remoteMessage => {
console.log('FCM Message Data:', remoteMessage.data);
});
As I understand this subscribes for cloud messages and when I send some cloud message notification from firebase-console, I should get console output; but nothing happens.
I dont know what am I missing but I think there is a big update on this package and most of docs are for previous version and I really stuck here thanks for assist
for rnfirebase.io V6
componentDidMount = async () => {
this.checkNotificationPermission();
await messaging().requestPermission({provisional: true});
await messaging().registerDeviceForRemoteMessages();
await this.getFCMToken();
if (Platform.OS === 'android') {
this.createAndroidNotificationChannel();
}
this.backgroundState();
this.foregroundState();
};
checkNotificationPermission = () => {
firebase
.messaging()
.hasPermission()
.then(enabled => {
if (!enabled) {
this.promptForNotificationPermission();
}
});
};
promptForNotificationPermission = () => {
firebase
.messaging()
.requestPermission({provisional: true})
.then(() => {
console.log('Permission granted.');
})
.catch(() => {
console.log('Permission rejected.');
});
};
createAndroidNotificationChannel() {
const channel = new firebase.notifications.Android.Channel(
'channelId',
'Push Notification',
firebase.notifications.Android.Importance.Max,
).setDescription('Turn on to receive push notification');
firebase.notifications().android.createChannel(channel);
}
foregroundState = () => {
const unsubscribe = messaging().onMessage(async notification => {
console.log('Message handled in the foregroundState!', notification);
});
return unsubscribe;
};
// Register background handler
backgroundState = () => {
messaging().setBackgroundMessageHandler(async notification => {
console.log('Message handled in the background!', notification);
});
};
Has anyone worked with notifications on ionic 3? I'm trying to create some apps that store fcm notification, I'm trying most of the tutorials out there but nothing seems working. When I get notification and tap it, I can't get the message.
Here's some code that I've tried
initializeApp() {
this.platform.ready().then(() => {
// START
this.fcm.getToken().then(token => {
console.log(token);
alert('token: '+token);
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log(token);
alert('refresh token: '+token);
});
this.fcm.onNotification().subscribe(data => {
alert('data: '+data);
if(data.wasTapped){
console.log("Received in background " + JSON.stringify(data) );
alert("Received in background " + JSON.stringify(data) );
this.nav.setRoot(InboxnotifPage, {data: data});
} else {
console.log("Received in foreground" + JSON.stringify(data) );
alert("Received in foreground" + JSON.stringify(data) );
this.nav.push(InboxnotifPage, {data: data});
};
});
// END
}
}
you have to add .plist file in your project build root to communicate with your device
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
alert('');
} else {
console.log("Received in foreground");
// this.presentToast("Received in foreground");
}
});
this.getToken();
this.fcm.onTokenRefresh().subscribe(token => {
this.rest.globalToken = token;
});
});
follow the original documentation and please first of all check notification from https://console.firebase.google.com then pass token to rest Api
I have an Ionic mobile application that receives notifications from the Firebase console. The application correctly receives notifications in background and foreground. However, when I send notifications from Node.js with firebase-admin plugin, only foreground notification arrives. Notifications do not arrive when the application is in the background.
What could be the problem? Does anyone know why the mobile app receive notifications in background with Firebase console but not with Node.js?
Thanks for any idea.
This is the code in the mobile application (app.component.ts):
this.fcm.subscribeToTopic('all');
platform.ready().then(() => {
this.fcm.getToken().then(token => {
console.log(token);
let alert = this.alertCtrl.create({
title: '¡new notification!',
message: token,
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('cancel button');
}
},
{
text: 'OK',
handler: () => {
console.log('ok button');
this.navCtrl.push('DetailPage');
}
}
]
});
alert.present();
});
this.fcm.onNotification().subscribe(data => {
alert('message received')
if(data.wasTapped) {
console.info("Received in background");
} else {
console.info("Received in foreground");
};
});
statusBar.styleDefault();
splashScreen.hide();
});
This is the code in Node.js:
var sys = require("util");
var admin = require('firebase-admin');
var serviceAccount = require('./xxxx.json');
var registrationToken ="xxxxxx";
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxx"
});
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
admin.messaging().send(message)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error){
console.log("Error sending message", error);
});