Reputation: 49
I've created an app with ionic angular using capacitor. users can create groups and chat with each other. so in firebase, I'm able to send push notifications to specific tokens and it works fine. but how can I send it in app, not in the firebase console?
example: when user A wants to join group B user B gets a notification like " [userA.name] wants to join your group " or " you have a new message from [userC.name] "
import { Injectable } from '@angular/core';
import {Capacitor} from '@capacitor/core';
import {
ActionPerformed,
PushNotificationSchema,
PushNotifications,
Token,
} from '@capacitor/push-notifications';
@Injectable({
providedIn: 'root'
})
export class NotificationsService {
constructor() { }
initPush() {
if (Capacitor.getPlatform() !== 'web') {
this.registerPush();
}
}
public registerPush() {
PushNotifications.requestPermissions().then((permission) => {
if (permission.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// No permission for push granted
}
});
PushNotifications.addListener(
'registration',
(token: Token) => {
console.log('My token: ' + JSON.stringify(token));
}
);
PushNotifications.addListener('registrationError', (error: any) => {
console.log('Error: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
async (notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
async (notification: ActionPerformed) => {
const data = notification.notification.data;
console.log('Action performed: ' + JSON.stringify(notification.notification));
if (data.detailsId) {
//this.router.navigateByUrl(`/home/${data.detailsId}`);
}
}
);
}
}
Upvotes: 0
Views: 1054
Reputation: 599956
Sending a message through the FCM API is possible, but requires that you specify the so-called FCM server key, which means it cannot be securely done from without your client-side code. Instead you'll want to send the messages from a trusted environment (like a server, Cloud Functions or Cloud Run) and then invoke that from within your app.
For an example of this, see the function-samples
repo on Send Firebase Cloud Messaging notifications for new followers, which send a message through FCM when certain conditions are met in a Firestore write (which can then happen from the client-side code).
Also see:
Upvotes: 1