通知の動作

ここまでは、通知の表示形式を変更するオプションについて説明してきました。通知の動作を変更するオプションもあります。

デフォルトでは、視覚的なオプションのみを指定して showNotification() を呼び出すと、次のようになります。

  • 通知をクリックしても何も起こりません。
  • 新しい通知は 1 つずつ表示されます。ブラウザは通知を折りたたみません。
  • プラットフォームによっては、音を鳴らしたり、ユーザーのデバイスを振動させたりすることがあります。
  • プラットフォームによっては、通知が短時間で消えるものもあれば、ユーザーが操作するまで通知が表示されるものもあります。(たとえば、Android とパソコンの通知を比較します)。

このセクションでは、オプションのみを使用してこれらのデフォルトの動作を変更する方法について説明します。これらは比較的簡単に実装して活用できます。

通知クリック イベント

ユーザーが通知をクリックしたときのデフォルトの動作は、何も起こらないことです。通知を閉じたり削除したりすることもありません。

通知のクリックに対する一般的な処理は、通知を閉じて、他のロジックを実行することです(ウィンドウを開く、アプリケーションに対して API 呼び出しを行うなど)。

これを実現するには、'notificationclick' イベント リスナーをサービス ワーカーに追加する必要があります。これは、通知がクリックされるたびに呼び出されます。

self.addEventListener('notificationclick', (event) => {
  const clickedNotification = event.notification;
  clickedNotification.close();

  // Do something as the result of the notification click
  const promiseChain = doSomething();
  event.waitUntil(promiseChain);
});

この例に示すように、クリックされた通知には event.notification としてアクセスできます。ここから、通知のプロパティとメソッドにアクセスできます。この場合は、close() メソッドを呼び出して追加の処理を行います。

操作

アクションを使用すると、通知をクリックするだけでなく、ユーザーとの別のレベルのインタラクションを作成できます。

ボタン

前のセクションでは、showNotification() を呼び出すときにアクション ボタンを定義する方法について説明しました。

const title = 'Actions Notification';

const options = {
  actions: [
    {
      action: 'coffee-action',
      title: 'Coffee',
      type: 'button',
      icon: '/images/demos/action-1-128x128.png',
    },
    {
      action: 'doughnut-action',
      type: 'button',
      title: 'Doughnut',
      icon: '/images/demos/action-2-128x128.png',
    },
    {
      action: 'gramophone-action',
      type: 'button',
      title: 'Gramophone',
      icon: '/images/demos/action-3-128x128.png',
    },
    {
      action: 'atom-action',
      type: 'button',
      title: 'Atom',
      icon: '/images/demos/action-4-128x128.png',
    },
  ],
};

registration.showNotification(title, options);

ユーザーが操作ボタンをクリックした場合は、noticationclick イベントの event.action 値をチェックして、クリックされた操作ボタンを特定します。

event.action には、オプションで設定された action 値が含まれます。上記の例では、event.action 値は 'coffee-action'、'doughnut-action'、'gramophone-action'、'atom-action' のいずれかになります。

これにより、次のように通知のクリックやアクションのクリックを検出できます。

self.addEventListener('notificationclick', (event) => {
  if (!event.action) {
    // Was a normal notification click
    console.log('Notification Click.');
    return;
  }

  switch (event.action) {
    case 'coffee-action':
      console.log("User ❤️️'s coffee.");
      break;
    case 'doughnut-action':
      console.log("User ❤️️'s doughnuts.");
      break;
    case 'gramophone-action':
      console.log("User ❤️️'s music.");
      break;
    case 'atom-action':
      console.log("User ❤️️'s science.");
      break;
    default:
      console.log(`Unknown action clicked: '${event.action}'`);
      break;
  }
});

インライン返信

また、前のセクションでは、通知にインライン返信を追加する方法を説明しました。

const title = 'Poll';

const options = {
  body: 'Do you like this photo?',
  image: '/images/demos/cat-image.jpg',
  icon: '/images/demos/icon-512x512.png',
  badge: '/images/demos/badge-128x128.png',
  actions: [
    {
      action: 'yes',
      type: 'button',
      title: '👍 Yes',
    },
    {
      action: 'no',
      type: 'text',
      title: '👎 No (explain why)',
      placeholder: 'Type your explanation here',
    },
  ],
};

registration.showNotification(title, options);

event.reply には、ユーザーが入力フィールドに入力した値が格納されます。

self.addEventListener('notificationclick', (event) => {
  const reply = event.reply;

  // Do something with the user's reply
  const promiseChain = doSomething(reply);
  event.waitUntil(promiseChain);
});

タグ

tag オプションは、基本的に通知を「グループ化」する文字列 ID であり、複数の通知をユーザーに表示する方法を簡単に決定できます。例を挙げて説明するのが最も簡単です。

通知を表示して、'message-group-1' のタグを付けましょう。次のコードで通知を表示します。

const title = 'Notification 1 of 3';

const options = {
  body: "With 'tag' of 'message-group-1'",
  tag: 'message-group-1',
};

registration.showNotification(title, options);

最初の通知が表示されます。

メッセージ グループ 1 のタグが付いた最初の通知。

次のように、'message-group-2' の新しいタグを使用して 2 つ目の通知を表示してみましょう。

const title = 'Notification 2 of 3';

const options = {
  body: "With 'tag' of 'message-group-2'",
  tag: 'message-group-2',
};

registration.showNotification(title, options);

これにより、2 つ目の通知がユーザーに表示されます。

メッセージ グループ 2 の 2 番目のタグが付いた 2 つの通知。

次に、3 つ目の通知を表示しますが、最初のタグ 'message-group-1' を再利用します。これにより、最初の通知が閉じられ、新しい通知に置き換えられます。

const title = 'Notification 3 of 3';

const options = {
  body: "With 'tag' of 'message-group-1'",
  tag: 'message-group-1',
};

registration.showNotification(title, options);

showNotification() が 3 回呼び出されたにもかかわらず、通知は 2 つになりました。

2 つの通知。最初の通知が 3 つ目の通知に置き換えられます。

tag オプションは、メッセージをグループ化するための簡単な方法です。現在表示されている古い通知が新しい通知と同じタグを持っている場合、古い通知は閉じられます。

tag を使用する際の注意点として、通知を置き換える場合、音やバイブレーションは発生しません。

そこで renotify オプションの出番です。

再通知

これは、執筆時点では主にモバイル デバイスに適用されます。このオプションを設定すると、新しい通知でバイブレーションが作動し、システム音が再生されます。

置き換え通知をサイレントに更新するのではなく、ユーザーに通知したい場合があります。チャット アプリケーションはその好例です。この場合は、tag と renotify を true に設定する必要があります。

const title = 'Notification 2 of 2';

const options = {
  tag: 'renotify',
  renotify: true,
};

registration.showNotification(title, options);

サイレント

このオプションを使用すると、新しい通知を表示できますが、バイブレーション、音、デバイスのディスプレイのオンといったデフォルトの動作は行われません。

これは、通知がユーザーの即時の注意を必要としない場合に最適です。

const title = 'Silent Notification';

const options = {
  silent: true,
};

registration.showNotification(title, options);

操作が必要

パソコン版 Chrome では、通知が一定期間表示された後に非表示になります。Android 版 Chrome にはこの動作はありません。通知は、ユーザーが操作するまで表示されます。

ユーザーが操作するまで通知を表示したままにするには、requireInteraction オプションを追加します。これにより、ユーザーが通知を閉じるかクリックするまで通知が表示されます。

const title = 'Require Interaction Notification';

const options = {
  requireInteraction: true,
};

registration.showNotification(title, options);

このオプションは慎重に使用してください。通知を表示して、ユーザーが通知を閉じるために行っている操作を強制的に停止させると、ユーザーに不快感を与える可能性があります。

次のセクションでは、通知の管理や、通知がクリックされたときにページを開くなどのアクションの実行にウェブで使用される一般的なパターンをいくつか見ていきます。

次のステップ

Codelab