Use Notifications API

This commit is contained in:
Ben Goldsworthy 2021-03-21 14:46:26 +00:00
parent c0276dd253
commit 5a0c5cbded
5 changed files with 83 additions and 42 deletions

View file

@ -13,16 +13,14 @@ export class AppComponent {
constructor(private messagingService: MessagingService) { }
ngOnInit() {
this.userType = localStorage.getItem('usertype');
if (this.userType === 'customer') {
/**
* Checks for push notification permissions and subscribes to messages.
*/
ngOnInit(): void {
if (localStorage.getItem('usertype') === 'customer') {
this.messagingService.requestPermission();
this.messagingService.receiveMessage();
this.message = this.messagingService.currentMessage;
console.log(this.message);
if (this.message.notification) {
console.log('Notification waiting');
}
}
}
}

View file

@ -66,19 +66,19 @@ export class SendPushNotificationComponent implements OnInit {
.subscribe(
result => {
if ( result.success === true ) {
console.log('Successful Upload');
console.debug('Message successfully sent.');
this.sendMessageFormStatus = 'success';
this.sendMessageForm.patchValue({
messagetext: '',
});
} else {
console.error('Upload Error');
console.error('Message send failed (1).');
this.sendMessageFormStatusError = JSON.stringify(result.status) + 'Error, ' + JSON.stringify(result.message);
this.sendMessageFormStatus = 'send_failed';
}
},
error => {
console.error('Upload Error');
console.error('Message send failed (0).');
try {
this.sendMessageFormStatusError = '"' + error.error.error + '" Error, ' + error.error.message;
} catch (e) {

View file

@ -4,7 +4,6 @@ import { AngularFireMessaging } from '@angular/fire/messaging';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class MessagingService {
currentMessage = new BehaviorSubject(null);
@ -13,37 +12,53 @@ export class MessagingService {
private api: ApiService
) { }
requestPermission() {
/**
* Requests user consent to send push notifications if this has not been
* granted and has not been previously denied (i.e., it won't spam people).
*/
requestPermission(): void {
if (!('Notification' in window)) {
alert('This browser does not support notifications.');
console.warn('This browser does not support the Notifications API.');
return;
} else if (Notification.permission === 'granted') {
console.log('Push notification permission granted');
this.registerDeviceToken();
} else if (Notification.permission === 'denied' ||
Notification.permission === 'default') {
console.log('Push notification permission not granted');
Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
console.log('Push notification permission granted');
this.registerDeviceToken();
}
});
}
switch (Notification.permission) {
case 'granted':
console.debug('Push notification permission granted');
this.registerDeviceToken();
break;
case 'denied':
console.debug('Push notification permission refused');
break;
default:
console.debug('Push notification permission not granted');
Notification.requestPermission().then(function(permission: string) {
if (permission === 'granted') {
console.debug('Push notification permission granted');
this.registerDeviceToken();
}
});
}
}
registerDeviceToken() {
this.angularFireMessaging.requestToken.subscribe((token) => {
/**
* Request a unique token for a given device and send it to the server to store
* in the database (if it doesn't already exist).
*/
registerDeviceToken(): void {
this.angularFireMessaging.requestToken.subscribe((token: string) => {
this.api.checkDeviceToken({'token': token}).subscribe(
result => {
if (result.exists) { console.log('Device already registered!'); } else {
if (result.exists) {
console.debug('Device already registered.');
} else {
this.api.addDeviceToken({'token': token, 'email': localStorage.getItem('email')}).subscribe(
result => {
console.log('Device registered successfully!');
console.debug('Device registered successfully.');
localStorage.setItem('devicetoken', token);
},
error => {
console.error('Device could not be registered!', error._body);
console.error('Device could not be registered.', error._body);
}
);
}
@ -53,15 +68,38 @@ export class MessagingService {
}
);
}, (err) => {
console.error('Unable to get permission to notify.', err);
console.error('Unable to get token.', err);
});
}
receiveMessage() {
/**
* Display a newly-received message as a Notification.
*/
receiveMessage(): void {
this.angularFireMessaging.messages.subscribe((message) => {
console.log('show message!', message);
const notification = new Notification(message.notification.title, { body: message.notification.body });
console.debug('Message received:', message);
this.displayNotification(message['notification']);
this.currentMessage.next(message);
});
}
/**
* Display a message as a notification (if the Notifications API) is supported,
* or an alert (if not).
*
* @param notification The notification object to display.
*/
displayNotification(notification): void {
if (!('Notification' in window)) {
console.warn('This browser does not support the Notifications API.');
window.alert(`${notification.title}\n${notification.body}`);
} else {
console.log(window.location.origin);
var options = {
body: notification.body,
icon: window.location.origin + "/assets/img/logo-128.png",
}
const noti = new Notification(notification.title, options);
}
}
}

View file

@ -10,13 +10,13 @@ export const environment = {
enableAnalytics: false,
analyticsKey: 'CHANGEME',
firebase: {
apiKey: 'CHANGEME',
authDomain: 'CHANGEME.firebaseapp.com',
databaseURL: 'CHANGEME.firebaseio.com',
projectId: 'CHANGEME',
storageBucket: 'CHANGEME.appspot.com',
messagingSenderId: 'CHANGEME',
appId: 'CHANGEME',
measurementId: 'G-CHANGEME'
apiKey: "AIzaSyB-iIcMH_eyfFT043_8pSGX3YYugpjm3Fg",
authDomain: "localspend-47012.firebaseapp.com",
databaseURL: "https://localspend-47012.firebaseio.com",
projectId: "localspend-47012",
storageBucket: "localspend-47012.appspot.com",
messagingSenderId: "469562689216",
appId: "1:469562689216:web:567a20c57c123f17354f25",
measurementId: "G-KL7BGT2EW0"
}
};

View file

@ -1,3 +1,8 @@
/**
* A Web Worker for sending and receiving messages using the Firebase Cloud
* Messaging (FCM) service.
*/
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');