PWAの根幹技術、Notifications APIの使い方
アプリでは当たり前になっているプッシュ通知ですが、Webブラウザ向けにはNotifications APIが用意されています。スマートフォンではまだ実装されていませんが、デスクトップ向けであれば十分使える状態になっています(Notifications APIはPush APIとは別です)。
今回はNotifications APIの実装方法を紹介します。
Notifications APIとPush APIの違い
Push APIはサーバからブラウザに対してプッシュ通知を送る仕組みで、Service Workerを利用します。Notifications APIはサーバサイドが不要で使えますが、Webブラウザがそのサイトを表示している時にしか使えません。
許可状態を知る
まず大事なのがユーザが通知を受け取ると許可しているかどうかです。それを調べるには Notification.permission を使います。値は3つあります。
- default
まだ許可を求めていません(初期値) - granted
通知を許可しています - denied
明確に拒否しています
そのため、deniedの時には処理を行わないというのが基本になるでしょう。
許可を得る
許可を得るのは Notification.requestPermission(); で行います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Notification.requestPermission(permission => { | |
if (permission === "granted") { | |
// 許可した場合 | |
} | |
}); |
grantedが得られれば許可を得た状態です。
通知を作成する
通知はこんな形で簡単に作成できます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var options = { | |
body: 'メッセージ本文', | |
icon: 'img/icon.png' | |
} | |
var n = new Notification('メッセージタイトル', options); |
通知を閉じる
表示した通知を閉じる場合は、通知オブジェクトのcloseを使います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n.close.bind(n) |
通知のイベント
通知には幾つかのイベントが設定されています。
- onclick
通知をクリックした時に呼ばれます
- onerror
エラーが出た時に呼ばれます
- onclose
閉じた際に呼ばれます
- onshow
表示した時に呼ばれます
使いどころ
Notifications APIはWebページを表示している時にしか使えません。そのため、アプリのプッシュ通知のように使っていないユーザを呼び起こすのには向きません。むしろ時間がかかる処理でユーザを待たせてしまう時に完了をお知らせしたり、チャットなどで別ページを開いている時にお知らせすると言った使い方になるでしょう。
まとめ
WebSocketなどと組み合わせればサーバから通知を出したい時に命令を出すと言った使い方はできそうです。とは言え、基本的にはWebページ上で起きた変化をユーザに気付かせると言った目的で使うのが良さそうです。
コメントは受け付けていません。