この Codelab では、Notifications API の基本機能を使用して、次のことを行います。
- 通知を送信する権限をリクエストする
- 通知を送信する
- 通知オプションをテストする
スターター アプリとそのコードを理解する
まず、新しい Chrome タブでライブアプリを確認します。
`Control+Shift+J`(Mac の場合は `Command+Option+J`)を押して DevTools を開きます。[コンソール] タブをクリックします。
コンソールに次のメッセージが表示されます。
Notification permission is default
意味がわからなくても心配しないでください。すぐにすべてが明らかになります。
ライブアプリの [通知を送信する権限をリクエスト] ボタンと [通知を送信] ボタンをクリックします。
コンソールには、いくつかの関数スタブ(
requestPermission
とsendNotification
)からの「TODO」メッセージが出力されます。これらは、この Codelab で実装する関数です。
次に、サンプルアプリのコードを見てみましょう。public/index.js
を開き、既存のコードの重要な部分を確認します。
showPermission
関数は Notifications API を使用してサイトの現在の権限の状態を取得し、コンソールに記録します。// Print current permission state to console; // update onscreen message. function showPermission() { let permission = Notification.permission; console.log('Notification permission is ' + permission); let p = document.getElementById('permission'); p.textContent = 'Notification permission is ' + permission; }
権限をリクエストする前は、権限の状態は
default
です。default
権限の状態では、サイトは通知を送信する前に権限をリクエストして許可を得る必要があります。requestPermission
関数はスタブです。// Use the Notification API to request permission to send notifications. function requestPermission() { console.log('TODO: Implement requestPermission()'); }
この関数は次のステップで実装します。
sendNotification
関数はスタブです。// Use the Notification constructor to create and send a new Notification. function sendNotification() { console.log('TODO: Implement sendNotification()'); }
この関数は、
requestPermission
を実装した後に実装します。window.onload
イベント リスナーは、ページの読み込み時にshowPermission
関数を呼び出し、現在の権限の状態をコンソールとページに表示します。window.onload = () => { showPermission(); };
通知を送信する権限をリクエストする
このステップでは、通知を送信するユーザーの権限をリクエストする機能を追加します。
Notification.requestPermission()
メソッドを使用して、ユーザーにサイトからの通知を許可またはブロックするよう求めるポップアップをトリガーします。
public/index.js の
requestPermission
関数スタブを次のコードに置き換えます。// Use the Notification API to request permission to send notifications. function requestPermission() { Notification.requestPermission() .then((permission) => { console.log('Promise resolved: ' + permission); showPermission(); }) .catch((error) => { console.log('Promise was rejected'); console.log(error); }); }
ライブアプリを表示している Chrome タブを再読み込みします。
ライブアプリのインターフェースで、[通知を送信する権限をリクエスト] をクリックします。ポップアップが表示されます。
ユーザーは、権限ポップアップに対して次の 3 つのいずれかの応答を行うことができます。
ユーザーの回答 | 通知権限の状態 |
---|---|
ユーザーが [許可] を選択する | granted |
ユーザーが [ブロック] を選択します。 | denied |
ユーザーが選択を行わずにポップアップを閉じる | default |
ユーザーが [許可] をクリックした場合:
Notification.permission
がgranted
に設定されている。サイトで通知を表示できるようになります。
その後の
Notification.requestPermission
の呼び出しは、ポップアップなしでgranted
に解決されます。
お客様が [ブロック] をクリックした場合:
Notification.permission
がdenied
に設定されている。サイトはユーザーに通知を表示できなくなります。
その後の
Notification.requestPermission
の呼び出しは、ポップアップなしでdenied
に解決されます。
お客様がポップアップを閉じた場合:
Notification.permission
はdefault
のままです。サイトでユーザーに通知を表示できなくなります。
Notification.requestPermission
を呼び出すたびに、ポップアップが追加で表示されます。ただし、ユーザーがポップアップを閉じ続けると、ブラウザがサイトをブロックし、
Notification.permission
がdenied
に設定されることがあります。権限リクエストのポップアップも通知もユーザーに表示されなくなります。この記事の執筆時点では、通知の許可を求めるポップアップが閉じられたときのブラウザの動作は変更される可能性があります。この問題を解決する最善の方法は、ユーザーが開始した操作に応じて常に通知権限をリクエストすることです。これにより、ユーザーは通知権限のリクエストを予期し、何が起こっているかを把握できます。
通知を送信する
このステップでは、ユーザーに通知を送信します。
Notification
コンストラクタを使用して新しい通知を作成し、表示を試みます。権限の状態が granted
の場合、通知が表示されます。
index.js の
sendNotification
関数スタブを次のコードに置き換えます。// Use the Notification constructor to create and send a new Notification. function sendNotification() { let title = 'Test'; let options = { body: 'Test body', // Other options can go here }; console.log('Creating new notification'); let notification = new Notification(title, options); }
Notification
コンストラクタは、title
とoptions
の 2 つのパラメータを取ります。options
は、通知に含めることができる視覚設定とデータを表すプロパティを持つオブジェクトです。詳しくは、通知パラメータに関する MDN ドキュメントをご覧ください。ライブアプリを表示している Chrome タブを更新し、[通知を送信] ボタンをクリックします。
Test body
というテキストを含む通知が表示されます。
権限なしで通知を送信した場合
このステップでは、ユーザーの権限なしで通知を表示しようとしたときに何が起こるかを確認するためのコードを数行追加します。
public/index.js
のsendNotification
関数の最後に、新しい通知のonerror
イベント ハンドラを定義します。
// Use the Notification constructor to create and send a new Notification.
function sendNotification() {
let title = 'Test';
let options = {
body: 'Test body',
// Other options can go here
};
console.log('Creating new notification');
let notification = new Notification(title, options);
notification.onerror = (event) => {
console.log('Could not send notification');
console.log(event);
};
}
通知権限エラーを観察するには:
Chrome の URL バーの横にある鍵アイコンをクリックし、サイトの通知権限の設定をデフォルトにリセットします。
[通知の送信を許可する] をクリックし、今回はポップアップから [ブロック] を選択します。
[通知を送信] をクリックして、何が起こるかを確認します。エラー テキスト(
Could not send notification
)とイベント オブジェクトがコンソールに記録されます。
必要に応じて、サイトの通知権限を再度リセットします。権限をリクエストしてポップアップを複数回閉じ、何が起こるかを確認できます。
通知オプションをテストする
これで、権限をリクエストして通知を送信する方法の基本を学びました。また、ユーザーのレスポンスがアプリの通知表示機能にどのような影響を与えるかについても説明しました。
通知を作成する際に利用できるさまざまなビジュアル オプションやデータ オプションを試すことができるようになりました。使用可能なオプションの全リストは次のとおりです。(これらのオプションの詳細については、MDN の通知に関するドキュメントをご覧ください)。
ブラウザやデバイスによってこれらのオプションの実装が異なるため、さまざまなプラットフォームで通知をテストして、どのように表示されるかを確認することをおすすめします。
let options = {
dir: 'auto', // Text direction
lang: 'en-US', // A language tag
badge: '/orange-cat.png', // Display when insufficient room
body: 'Hello World', // Body text
tag: 'mytag', // Tag for categorization
icon: '/line-cat.png', // To display in the notification
image: '/orange-cat.png', // To display in the notification
data: { // Arbitrary data; any data type
cheese: 'I like cheese',
pizza: 'Excellent cheese delivery mechanism',
arbitrary: {
faveNumber: 42,
myBool: true
}},
vibrate: [200, 100, 200], // Vibration pattern for hardware
renotify: false, // Notify if replaced? Default false
requireInteraction: false,// Active until click? Default false
/*
actions: // Array of NotificationActions
// Only usable with a service worker
[{
action: 'shop',
title: 'Shop!',
icon: '/bags.png'
},],
*/
}
Peter Beverloo の通知ジェネレータで、さらにアイデアを探してみましょう。
このシリーズの次の Codelab「サービス ワーカーで通知を処理する」で、さらに詳しく見てみましょう。