8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Webnotificationsで通知領域を表示する時間を設定する。

Posted at

Webnotificationsでの通知設定

Webnotificationsを使えば、何かイベントが発生したときに、通知領域にメッセージを表示させる事ができる。
Socketo.ioと合わせて使うと、Webアプリでイベントが発生した事をすぐにユーザに通知する事ができる。
例えば、以下のような感じで。

            socket.on('get_msg', function(data){
                notification = new window.Notification(data.name,{
                    body: data.msg
                });
            });

この記述では、socket.ioでget_msgを受信した時に、通知領域に受け取ったdata.nameとdata,msgを表示する用になる。
ただ、このままだと表示された通知が5秒くらいで、自動で消えてしまった。(safari7とFirefox30で確認)
setTimeoutを使えば通知を表示する期間を調整できるみたいなので、1秒後に通知が消えるように修正すると以下のようになる。

            socket.on('get_msg', function(data){
                notification = new window.Notification(data.name,{
                    body: data.msg
                });
                setTimeout(function(){
                  notification.cancel();
                },1000);
            });

setTimeoutの1つ目の引数で実行する処理を記述する。今回は通知を閉じる処理を記述した。2つ目の引数で実行するまでの待ち時間をmsで記述する。
この記述だと、1000ms後(1秒後)に通知を閉じる処理が走る。
実行してみたところ、Safari7では1秒後に通知が消えたが、Firefox30では、setTimeoutを指定していないのと同じ時間が経過後に、通知が消えた。
また、待ち時間を5000ms(5秒)以上の値にしても、通知の表示時間が延びる事は無かった。

ここにも記載があるが、そもそも通知をブラウザが自動で閉じるのは、Webnotificationsの仕様に従ってないようで。。。
https://developer.mozilla.org/ja/docs/WebAPI/Using_Web_Notifications

便利な機能だけど、まだまだブラウザによって実装がまちまちな感じ。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?