タイムリーで有用な通知をユーザーに配信します。
プッシュ通知は、W3C のウェブ アプリケーション ワーキング グループの一部である Push API と Notification API のリリースにより、2016 年に標準化されました。これらの API は、ウェブ デベロッパーがウェブアプリにプッシュ通知を組み込むために必要な機能と、ユーザーがウェブブラウザで通知を受信して操作するために必要な機能を提供します。プッシュ メッセージは、ユーザーが通知の送信を許可したウェブサイトまたはアプリからユーザーのウェブブラウザに送信される通知です。これらのメッセージは、新しいコンテンツや最新情報の通知、今後のイベントや期限のリマインダー、その他の重要な情報の提供に使用できます。プッシュ メッセージは、ニュースアプリやスポーツアプリなど、ユーザーにタイムリーで関連性の高い情報を提供する必要のあるアプリや、特別な特典やセールに関する通知をユーザーに送信する必要がある e コマース ウェブサイトに特に便利です。
プッシュ通知に登録するには、まず、ブラウザがプッシュ通知をサポートしているかどうかを確認します。そのためには、navigator
オブジェクトと window
オブジェクトで serviceWorker
オブジェクトと PushManager
オブジェクトを確認します。
push 通知がサポートされている場合は、async
キーワードと await
キーワードを使用してサービス ワーカーを登録し、push 通知をサブスクライブします。JavaScript を使用してこれを行う方法の例を次に示します。
// Check if the browser supports push notifications.
if ("serviceWorker" in navigator && "PushManager" in window) {
try {
// Register the service worker.
const swReg = await navigator.serviceWorker.register("/sw.js");
// Subscribe for push notifications.
const pushSubscription = await swReg.pushManager.subscribe({
userVisibleOnly: true
});
// Save the push subscription to the database.
savePushSubscription(pushSubscription);
} catch (error) {
// Handle errors.
console.error("Error subscribing for push notifications.", error);
}
} else {
// Push notifications are not supported by the browser.
console.error("Push notifications are not supported by the browser.");
}