This guide will walk you through the process of setting up web push notifications with Go-Mailer.
Web push notifications are small messages that you send from your applications or website to your user's browser. These messages will be displayed to your user even when they are not actively using the browser.
Before proceeding with the setup, you need to generate your API Key. The API key enables secure communications between your application and the Go-Mailer servers.
On your Go-Mailer account, navigate to Settings > Developers. Click on the Generate API key button to generate your API key.
Once your API Key is generated, you would need to configure the Go-Mailer Web Push SDK in your javascript web application. The SDK provides simple utility that enable you to capture notification permissions as well as store the permission credentials on our servers.
To receive and display web push notifications, you need to create a file named gm-service-worker.js in your root or public directory. Next, copy the following into that file.
const logAction = async (tracking_id) => {
try {
await fetch(`https://messaging.go-mailer.com/webhooks/push/web/${tracking_id}`);
} catch (e) {
console.log("Unable to log action");
return null;
}
};
const tracker = { tracking_id: "" };
self.addEventListener("push", (event) => {
if (!event.data) return;
const { title, body, icon, tracking_id } = event.data.json();
tracker.tracking_id = tracking_id;
const promiseChain = self.registration.showNotification(title, { body, icon });
event.waitUntil(promiseChain);
});
self.addEventListener("notificationclick", (event) => {
const clickedNotification = event.notification;
clickedNotification.close();
const promiseChain = logAction(tracker.tracking_id);
event.waitUntil(promiseChain);
});Finally, you will need to register the gm-service-worker.js file. To do this, call the register() function in the SDK. This function can be called anywhere within your app, however, we advise that it be called at the application's root or main file.
import GoMailerWebPush from "@go-mailer/web-push";
GoMailerWebPush.register(<api_key>);As noted earlier, web push only works with contact profiles. Go-Mailer identifies your contacts or users by their email address, therefore you MUST send the contact's email address along with the permission data.
We have provided a utility function that collects and stores the user's permission. All you need to do is pass in the user's email address and any extra user information.
import GoMailerWebPush from "@go-mailer/web-push";
// your code
GoMailerWebPush.requestPermission().then(subscription_token => {
if (subscription_token) {
GoMailerWebPush.saveSubscriptionToken(subscription_token, { email });
}
});
// your codeNOTE: If the user does not exist in your Go-Mailer account, a new contact will be created.
Congratulations, you have successfully integrated with Go-Mailer's web push notifications.