Push 通知の購読
ユーザーのブラウザで Push 通知を受け取るには、フロントエンドで購読登録を行う必要があります。
- アプリの VAPID 公開鍵(ダッシュボードのアプリ詳細画面で確認)
subscribe_onlyスコープの API キー
Service Worker の準備
Section titled “Service Worker の準備”まず Service Worker ファイルを作成します。
self.addEventListener("push", (event) => { const data = event.data?.json() ?? {}; event.waitUntil( self.registration.showNotification(data.title ?? "通知", { body: data.body, icon: data.icon, badge: data.badge, data: { url: data.url }, }) );});
self.addEventListener("notificationclick", (event) => { event.notification.close(); if (event.notification.data?.url) { event.waitUntil(clients.openWindow(event.notification.data.url)); }});SDK を使った実装
Section titled “SDK を使った実装”import { TodokeClient } from "@todoke/sdk";
const client = new TodokeClient({ appId: "your-app-id", apiKey: "pk_subscribe_only_key", vapidPublicKey: "BNfhTEO47qSR...", serviceWorkerPath: "/sw.js",});
// 購読登録(ブラウザの通知許可ダイアログが表示される)const subscription = await client.subscribe();console.log("購読完了:", subscription.id);
// 購読解除await client.unsubscribe(subscription.id);// 1. Service Worker を登録const registration = await navigator.serviceWorker.register("/sw.js");
// 2. Push 購読を取得const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array("BNfhTEO47qSR..."),});
// 3. todoke API に登録await fetch("https://todoke-api.naoto24kawa.workers.dev/api/v1/apps/YOUR_APP_ID/subscriptions", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer pk_subscribe_only_key", }, body: JSON.stringify({ endpoint: subscription.endpoint, p256dh: btoa(String.fromCharCode(...new Uint8Array(subscription.getKey("p256dh")))), auth: btoa(String.fromCharCode(...new Uint8Array(subscription.getKey("auth")))), platform: "desktop", }),});// SDKawait client.unsubscribe(subscriptionId);
// REST APIawait fetch( `https://todoke-api.naoto24kawa.workers.dev/api/v1/apps/${appId}/subscriptions/${subscriptionId}`, { method: "DELETE", headers: { "Authorization": "Bearer pk_subscribe_only_key" }, });ブラウザ対応
Section titled “ブラウザ対応”| ブラウザ | 対応状況 |
|---|---|
| Chrome / Edge | ✅ |
| Firefox | ✅ |
| Safari 16.4+ (macOS / iOS) | ✅ |
| Safari 16.3 以前 | ❌ |