通知の動作

ここまで、通知の外観を変更するオプションを見てきました。通知の動作を変更するオプションもあります。

デフォルトでは、ビジュアル オプションのみを指定して showNotification() を呼び出すと、次のように動作します。

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

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

通知クリック イベント

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

通知のクリックは一般的に、通知を閉じて他のロジックを実行します(ウィンドウを開く、アプリに対して API 呼び出しを行うなど)。

そのためには、'notificationclick' イベント リスナーを Service Worker に追加する必要があります。このメソッドは、通知がクリックされるたびに呼び出されます。

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 つの通知。

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

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 件の通知があります。

最初の通知が 3 番目の通知に置き換わる 2 つの通知。

tag オプションは、単にメッセージをグループ化し、新しい通知と同じタグが付いている場合は、現在表示されている古い通知を閉じるための手段です。

tag を使用する際は注意すべき点として、通知を置き換える際に音やバイブレーションなしで置き換えられます。

ここで役立つのが renotify オプションです。

再通知

このドキュメントの作成時点では、主にモバイル デバイスに当てはまります。このオプションを設定すると、新しい通知が振動し、システム音が再生されます。

状況によっては、通知なく更新するのではなく、置換通知を使用してユーザーに通知したい場合があります。その好例が、チャット アプリケーションです。この場合、tagrenotifytrue に設定する必要があります。

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