Push
PurrCRM sends web pushes the way it sends a phone’s: through your own Firebase project, once your team has added its key on the Firebase key card of Settings › your app › Delivery › Push (A push campaign). The browser receives them through Firebase’s JavaScript messaging and a service worker of yours. The SDK brings no Firebase of its own: your app keeps Firebase, the permission prompt and the notifications, and hands the SDK the token and each push.
What you draw: the permission prompt’s lead-in (a button the user presses, since a browser asks only from a tap), a notice for a push that arrives while the page is open, and the inbox of notices with its bell. Firebase draws the system notification while the page is in the background.
Each push carries a plain notification (title and body) and its data in data: type (support_reply for a reply, crm_message for a message from your team), link (the page, such as /messages/<id>), notice_id, and nudge for a silent one.
1. Ask, and register the browser
Section titled “1. Ask, and register the browser”Firebase’s getToken needs your Firebase project’s web push certificate key (the VAPID key, from the Firebase console’s Project settings › Cloud Messaging › Web Push certificates) and the registration of your service worker (step 3). Ask for the permission from a tap, tell the SDK the answer, and hand it the token:
import { initializeApp } from "firebase/app";import { getMessaging, getToken, onMessage } from "firebase/messaging";import { crm } from "./crm";
const messaging = getMessaging(initializeApp(firebaseConfig));
export async function turnOnNotifications(): Promise<void> { const answer = await Notification.requestPermission(); // from a click await crm.permissionChanged("push", answer === "default" ? null : answer === "granted"); if (answer !== "granted") return; const serviceWorkerRegistration = await navigator.serviceWorker.register("/firebase-messaging-sw.js"); const token = await getToken(messaging, { vapidKey: VAPID_KEY, serviceWorkerRegistration }); await crm.registerPushToken(token);}Call registerPushToken on every load where the permission is granted, as Firebase may hand out a new token. The SDK registers it for the user signed in, and again for each user who signs in after, so a browser that changes hands gets only the new user’s pushes. It answers whether PurrCRM took it; one it did not is tried again at the next sign-in or call. The SDK registers one at a time: calling it again with the same token while that is on its way sends nothing more and answers what it answers, and a newer token waits for it.
The token is held in memory only, never kept in the browser. As a session ends the SDK lets go of it for that user, after a registration still on its way, so that the token is never left registered. Before your own sign-out, while the user’s token still works:
await crm.forgetPushToken();await mySignOut();Tell the SDK the permission whenever you learn it (on each load, too): crm.permissionChanged("push", allowed), with null for not asked yet. It records push_permission_changed only when an answer this browser already knew changes.
2. Hand over each push while the page is open
Section titled “2. Hand over each push while the page is open”onMessage(messaging, (payload) => { const result = crm.handlePushArrival(payload.data ?? {}); if (result.isCrm && !result.replyOnScreen && !result.silent) { showMyNotice(payload.notification); // yours to draw: a toast, a dot on the bell }});While the page is in front, Firebase hands the push to onMessage and shows no notification. handlePushArrival(data) answers a CrmPushResult:
isCrm: one of PurrCRM‘s pushes, which the SDK has acted on: a reply reads the unread count again, and a message from your team makes the SDK check in for in-app messages (at once on a test phone). Each one also reads the inbox of notices again.replyOnScreen: a reply in a conversation or ticket open on screen, which the conversation has already brought in and marked read. Show nothing for it.silent: a nudge to check in, with nothing to show.noticeId: the notice the push is, in the inbox.
3. The service worker forwards pushes and taps
Section titled “3. The service worker forwards pushes and taps”While the page is in the background or closed, Firebase’s service worker receives the push and shows the notification from its notification. Your service worker forwards the push’s data, and a tap on its notification, to the page, which hands them to the SDK. PurrCRM sends no webpush.fcm_options.link, so read the link from the data:
importScripts("https://www.gstatic.com/firebasejs/10.12.2/firebase-app-compat.js");importScripts("https://www.gstatic.com/firebasejs/10.12.2/firebase-messaging-compat.js");
firebase.initializeApp({ /* your Firebase config */ });
// A push arrived while no page was in front: tell the open pages.firebase.messaging().onBackgroundMessage(async (payload) => { for (const c of await clients.matchAll({ type: "window" })) { c.postMessage({ crmPush: "arrived", data: payload.data ?? {} }); }});
// The user tapped the notification: bring a page forward and tell it.self.addEventListener("notificationclick", (event) => { const data = event.notification.data?.FCM_MSG?.data ?? {}; event.notification.close(); event.waitUntil( (async () => { const [page] = await clients.matchAll({ type: "window", includeUncontrolled: true }); if (page) { await page.focus(); page.postMessage({ crmPush: "tapped", data }); } else { await clients.openWindow(`/?crm_push=${encodeURIComponent(JSON.stringify(data))}`); } })(), );});Use the same Firebase version in the service worker as in the page. In the page:
navigator.serviceWorker?.addEventListener("message", (e) => { if (e.data?.crmPush === "arrived") crm.handlePushArrival(e.data.data); if (e.data?.crmPush === "tapped") { if (!crm.handlePushTap(e.data.data)) myRouter.follow(e.data.data); // not PurrCRM's }});
// A page the tap opened reads the push from its own address.const pushed = new URLSearchParams(location.search).get("crm_push");if (pushed) crm.handlePushTap(JSON.parse(pushed));handlePushTap(data) records push_opened for any push, and answers whether PurrCRM takes the user where it goes: one of its pushes naming one of its pages, opened through your navigate hook once the user is ready (setReady). Any other tap is yours to follow.
Offers by push
Section titled “Offers by push”A marketing push goes only to people who agreed to offers by push. If your app asks them, tell PurrCRM:
await crm.setOffersByPush(true); // the consent as kept, or null when it could not be keptconst agreed = await crm.offersByPush(); // null when it could not be readTopics refine this further: see Preferences.
The inbox of notices
Section titled “The inbox of notices”Every push PurrCRM sends is also kept as a notice in the user’s inbox, so they can read it again in your app. crm.notices is a Value<CrmNotices>:
| Field | What it is |
|---|---|
notices | The notices read so far, newest first: each with id, type, title, body, link, createdAt and readAt (null while unread). |
unread | How many of all the user’s notices are unread: your bell’s count. |
loaded, loading | Read at least once; being read. |
failure | Why the last read failed, or null. |
nextBefore | Where the next page of older notices starts; empty when there are no more. |
The SDK reads the inbox as a user signs in, as the page comes back to the front, when one of PurrCRM‘s pushes arrives, and when a check-in says the count moved. Your inbox screen:
crm.notices.subscribe((inbox) => { bell.textContent = inbox.unread > 0 ? String(inbox.unread) : ""; list.replaceChildren( ...inbox.notices.map((n) => noticeRow(n, () => { void crm.markNoticesRead([n.id]); if (n.link !== "") crm.openLink(n.link); })), ); moreButton.hidden = inbox.nextBefore === "";});
moreButton.onclick = () => crm.moreNotices();refreshButton.onclick = () => crm.refreshNotices();markAllButton.onclick = () => crm.markNoticesRead([], { all: true });markNoticesRead(ids) marks those read (the ones the user has seen) and answers whether PurrCRM took it; { all: true } marks every one. crm.openLink(link) follows a notice’s link by the same rules as a link in a message (Links).
Check it works
Section titled “Check it works”Sign in to your site as yourself in a browser that registered its token, and add yourself under Testing › Preview on my phone. Then Push my phones, on the Send a test push card of Settings › your app › Delivery › Push, pushes to the devices you added, and any message’s Try it on my test phone reaches them. With debug on, the setup check’s Pushes rows say whether the permission is granted, the token registered and your handler wired, and Test a push registers the token again (Setup check). If nothing arrives, the push’s report and the Recent failures card on Settings › your app › Delivery › Push say why.