はじめに
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 クラスを作成し、コードをよりクリーンに保つことをおすすめします。ただし、これはこのチュートリアルの範囲外です。