Enable Push Notifications for Meteor Apps.
Add the package to your project:
meteor add xerdi:push-notificationsEvery client which want to receive incoming push notifications must firstly register and after that subscribe to the PushNotifications service.
import {PushNotifications} from 'meteor/xerdi:push-notifications';
PushNotifications.registerAndSubscribe();
// OR
await PushNotifications.register();
await PushNotifications.subscribe();Then on the server every subscribed client can be notified like:
import {VAPIDCredentials, PushNotifications} from 'meteor/xerdi:push-notifications';
Meteor.startup(function () {
// Sets the credentials in any possible way
VAPIDCredentials.auto().init();
// VAPIDCredentials.fromSecrets().init();
// VAPIDCredentials.fromEnv().init();
// VAPIDCredentials.fromSettings().init();
// Get the connection info of a users subscription (required)
const user = Meteor.users.findOne({});
const {subscriptions} = user.services.notifications;
for (let sub of subscriptions) {
PushNotifications.sendNotification(sub, {
title: 'Test notification',
opts: {
icon: '/icons/my-icon.png',
body: 'Hello World!'
}
});
}
});The PushNotifications class has the following members and methods:
registration : ServiceWorkerRegistrationThe service worker registration.subscription : PushSubscriptionThe push subscription.statusEitheruninitialized,unsupported,registeredorsubscribed.notifications()Gets the notifications of the current registration.registerAndSubscribe()Both registers and subscribes to push notifications.register()Registers a service worker.subscribe()Enables push notifications for the current user.unsubscribe()Destroys both the registration and subscriptions. This method has to be called beforeAccounts#onLogout, since it has to be logged in for it to work.sendNotification(sub, notification)Pushes a notification for the given subscription.requestPermission()Requests browser permission for receiving push notifications.
The VAPIDCredentials class has the following static factory methods:
#auto()Tries all underlying methods in the exact same order.#fromSecrets()Tries to get the values from Docker secrets under/run/secrets. Allowed keys arevapid-public-key,vapid-private-keyandvapid-contact-uri.#fromEnv()Tries to get the values fromprocess.env. Allowed keys areVAPID_PUBLIC_KEY,VAPID_PRIVATE_KEYandVAPID_CONTACT_URI.#fromSettings()Tries to get the values fromMeteor.settings. Don't forget to addsettings.jsonto your.gitignore.#create()Generates credentials withwebpush.generateVAPIDKeys.
Furthermore, the VAPIDCredentials has the following members and methods:
.isNewlyCreated : booleanWhether the credentials are newly created..contactUri : StringThe contact URI of this subscription..publicKey : StringThe public key..privateKey : StringThe private key..init()Sets the credentials for thewebpushservice..save()Stores the values in<project_dir>/settings.json.
Note: the build-plugin.js will store the credentials automatically if newly created.