タイムリーで有用な通知をユーザーに提供します。
プッシュ通知は、2016 年に W3C のウェブ アプリケーション ワーキング グループの一部である Push API と Notification API がリリースされ、標準化されました。これらの API は、ウェブ デベロッパーがプッシュ通知をウェブ アプリケーションに組み込んだり、ユーザーがウェブブラウザで通知を受信して操作したりするために必要な機能を提供します。プッシュ メッセージとは、ユーザーが以前に通知の送信権限を付与したウェブサイトまたはアプリケーションからユーザーのウェブブラウザに送信される通知です。これらのメッセージを使用して、新しいコンテンツやアップデートについてユーザーに注意喚起したり、今後のイベントや期限について注意を促したり、その他の重要な情報を提供できます。プッシュ メッセージは、ニュースアプリやスポーツアプリなど、関連性の高い情報をユーザーにタイムリーに配信する必要があるアプリケーションや、スペシャル オファーやセールに関する通知をユーザーに送信したい e コマース ウェブサイトで特に役立ちます。
プッシュ通知を登録するには、まず、navigator
オブジェクトと window
オブジェクトの serviceWorker
オブジェクトと PushManager
オブジェクトをチェックして、ブラウザがプッシュ通知をサポートしているかどうかを確認します。
プッシュ通知がサポートされている場合は、async
キーワードと await
キーワードを使用して Service Worker を登録し、プッシュ通知をサブスクライブします。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.");
}