はじめに
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 クラスを作成し、コードを整理しやすくすることもできますが、このチュートリアルでは扱いません。