はじめに
Notifications API を使用すると、特定のイベントについて、受動的な通知(新しいメール、ツイート、カレンダーの予定)とユーザー操作の両方で、どのタブにフォーカスがあるかに関係なく、ユーザーに通知を表示できます。ドラフト仕様はありますが、現在は標準ではありません。
次の簡単な手順に沿って、数分で通知を実装できます。
ステップ 1: Notifications API のサポートを確認する
webkitNotifications がサポートされているかどうかを確認します。webkitNotifications という名前は、ドラフト仕様の一部であるためです。最終的な仕様では、代わりに notifications() 関数になります。
// check for notifications support
// you can omit the 'window' keyword
if (window.webkitNotifications) {
console.log("Notifications are supported!");
}
else {
console.log("Notifications are not supported for this Browser/OS version yet.");
}
ステップ 2: ユーザーがウェブサイトに通知を表示する権限を付与できるようにする
ユーザーがウェブサイトに通知を表示する権限を手動で付与していない場合、上記のいずれのコンストラクタでもセキュリティ エラーがスローされます。例外を処理するには try-catch ステートメントを使用できますが、同じ目的で checkPermission メソッドを使用することもできます。
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
} else {
window.webkitNotifications.requestPermission();
}
}, false);
ウェブ アプリケーションに通知を表示する権限がない場合は、requestPermission メソッドによって情報バーが表示されます。
ただし、requestPermission メソッドは、未承諾のインフォバーを回避するために、ユーザー操作(マウスイベントやキーボード イベントなど)によってトリガーされるイベント ハンドラでのみ機能することを非常に重要に留意してください。この場合、ユーザー アクションは ID が「show_button」のボタンのクリックです。ユーザーが requestPermission をトリガーするボタンやリンクを明示的にクリックしていない限り、上記のスニペットは機能しません。
ステップ 3: リスナーとその他のアクションを接続する
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
notification_test = window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
notification_test.ondisplay = function() { ... do something ... };
notification_test.onclose = function() { ... do something else ... };
notification_test.show();
} else {
window.webkitNotifications.requestPermission();
}
}, false);
この時点で、コードをよりクリーンな状態に保つために、これらのイベントとアクションをすべてカプセル化して独自の Notification クラスを作成することもできますが、これはこのチュートリアルの範囲外です。