通知API

現行標準 — 最終更新

参加方法:
GitHub whatwg/notifications (新しい問題を作成, 既存の問題)
Matrixでチャット
コミット:
GitHub whatwg/notifications/commits
このコミット時点のスナップショット
@notifyapi
テスト:
web-platform-tests notifications/ (進行中の作業)
翻訳 (規範的ではありません):
日本語
简体中文
한국어

概要

この現行標準は、エンドユーザーに通知を表示するためのAPIを定義します。通常、トップレベルの閲覧コンテキストのビューポート外で表示されます。既存の通知システムと互換性を保ちながら、プラットフォームに依存しないよう設計されています。

1. 用語

この仕様書はInfra Standardに依存しています。 [INFRA]

この仕様書で使用されるいくつかの用語は、DOM、Fetch、高解像度時間、HTML、IDL、Service Workers、URL、およびVibration API標準で定義されています。 [DOM] [FETCH] [HR-TIME] [HTML] [WEBIDL] [SERVICE-WORKERS] [URL] [VIBRATION]

2. 通知

通知とは、 メッセージの配信など、何かが発生したことを抽象的に表現するものです。

通知には、 サービスワーカー登録(nullまたはサービスワーカー登録)が関連付けられています。初期値はnullです。

通知には、 タイトル(文字列)が関連付けられています。

通知には、 方向("auto"、"ltr"、または"rtl")が関連付けられています。

通知には、 言語(文字列)が関連付けられています。

通知には、 本文(文字列)が関連付けられています。

通知には、 ナビゲーションURL (nullまたはURL)が関連付けられています。初期値はnullです。

通知には、 タグ(文字列)が関連付けられています。

通知 (notification) には関連付けられた データ ( レコード) がある。

通知 (notification) には関連付けられた タイムスタンプ ( EpochTimeStamp) がある。

タイムスタンプは通知が実際に発生した時間を示すために使用されることがある。例えば、デバイスがオフラインのためにすぐに配信できなかったメッセージの通知の場合は過去の時間、またはこれから始まる会議の通知の場合は未来の時間を示すことがある。

通知 (notification) には関連付けられた オリジン (オリジン) がある。

通知 (notification) には関連付けられた 再通知の設定 (ブール値) がある。初期値は false。true の場合、新しい通知が既存の通知と同じ タグ を持つ場合に、通知表示手順が実行された後にエンドユーザーが再び通知されるべきことを示す。

通知 (notification) には関連付けられた サイレント設定 (null またはブール値) がある。初期値は null。true の場合、音や振動を発生させてはならないことを示す。null の場合は、音や振動の発生はプラットフォームの慣習に委ねられる。

通知 (notification) には関連付けられた インタラクション要求設定 (ブール値) がある。初期値は false。true の場合、十分に大きな画面を持つデバイスで通知が、エンドユーザーが通知をアクティブ化または解除するまで簡単にアクセス可能な状態で維持されるべきであることを示す。

通知 (notification) には以下の関連付けられたグラフィックスを持つことができる: 画像URL, アイコンURL, および バッジURL。また、それに対応する 画像リソース, アイコンリソース, および バッジリソース がある。

画像リソース は通知 (notification) の内容の一部として表示される画像で、アイコンリソースバッジリソース よりも高い視覚的優先度で表示されるべきだが、表示される機会は少ない可能性がある。

アイコンリソース は通知 (notification) を補完する画像 (例えばアイコンや送信者の写真) である。

バッジリソース はウェブアプリケーションを表すアイコン、またはウェブアプリケーションが多様な 通知 を送信する場合は通知のカテゴリを表すアイコンである。それは通知 (notification) 自身を表示するのに十分なスペースがない場合に通知を表すために使用されるかもしれない。また通知 (notification) 内部に表示されることもあるが、その場合は 画像リソースアイコンリソース よりも視覚的優先度が低いべきである。

通知 (notification) には関連付けられた 振動パターン (リスト) がある。初期値は « »。

開発者は、画像, アイコン, バッジ, または 振動パターン を通じてエンドユーザーにアクセスできない情報を伝達しないよう推奨される。特に、これらの機能をサポートしない通知プラットフォームがそれらを無視する可能性があるためである。

通知 (notification) には関連付けられた アクション (リスト、0個以上の通知アクションのリスト) がある。 通知アクション はエンドユーザーの選択肢を表す。それぞれの 通知アクション には以下が関連付けられる:

名前
文字列。
タイトル
文字列。
ナビゲーションURL
Null または URL。初期値は null。
アイコンURL
Null または URL。初期値は null。
アイコンリソース
Null またはリソース。初期値は null。

ユーザーは通知自体を有効化する代わりに、アクションを有効化することができます。 サポートされるアクションの最大数は、通知プラットフォームの制約の範囲内で、ゼロ以上の実装定義の整数です。

アクションの表示はプラットフォーム依存であるため、開発者は通知からエンドユーザーが実行できるすべてのアクションを、ウェブアプリケーション内でも利用可能にするよう推奨されます。

一部のプラットフォームでは、 アイコンリソースをプラットフォームのビジュアルスタイルにより適合させるために修正し、例えば角を丸めたり、特定の色で塗りつぶしたりして、エンドユーザーに表示する場合があります。開発者はそのようなケースに柔軟に対応でき、色の喪失や角の切り取りなどで重要な情報が失われないアイコンを使用することが推奨されます。

非永続的通知は、通知であり、 サービスワーカー登録がnullのものです。

(これはトラッキングベクターです) 永続的通知は、通知であり、 サービスワーカー登録がnullでないものです。


設定オブジェクトで通知を作成するには、文字列 titleNotificationOptions 辞書 options、および environment settings object settingsを受け取って行います:

  1. originsettingsoriginとします。

  2. baseURLsettingsAPIベースURLとします。

  3. fallbackTimestampを、Unixエポックから settings現在の壁時間までのミリ秒数(最も近い整数に丸める)とします。

  4. 通知を作成する処理を、titleoptionsoriginbaseURLfallbackTimestampを渡して実行し、その結果を返します。

通知を作成するには、文字列 titleNotificationOptions 辞書 optionsorigin originURL baseURLEpochTimeStamp fallbackTimestampを受け取って行います:

  1. notificationを新しい通知とします。

  2. もしoptions["silent"] がtrueであり、 options["vibrate"] 存在する場合、TypeErrorをスローします。

  3. もしoptions["renotify"] がtrueであり、 options["tag"] が空文字列の場合、TypeErrorをスローします。

  4. notificationdataStructuredSerializeForStorage(options["data"])の結果に設定します。

  5. notificationtitletitleに設定します。

  6. notificationdirectionoptions["dir"]に設定します。

  7. notificationlanguageoptions["lang"]に設定します。

  8. notificationoriginoriginに設定します。

  9. notificationbodyoptions["body"]に設定します。

  10. もしoptions["navigate"] 存在する場合、それをbaseURLパースし、失敗しない場合は notificationnavigation URLにその値を設定します。(失敗した場合、notificationnavigation URLはnullのままです。)

  11. notificationtagoptions["tag"]に設定します。

  12. もしoptions["image"] 存在する場合、それをbaseURLパースし、失敗しない場合は notificationimage URLにその値を設定します。(失敗した場合、notificationimage URLは設定しません。)

  13. もしoptions["icon"] 存在する場合、それをbaseURLパースし、失敗しない場合は notificationicon URLにその値を設定します。(失敗した場合、notificationicon URLは設定しません。)

  14. もしoptions["badge"] 存在する場合、それをbaseURLパースし、失敗しない場合は notificationbadge URLにその値を設定します。(失敗した場合、notificationbadge URLは設定しません。)

  15. もしoptions["vibrate"] 存在する場合、バリデートおよび正規化し、 notificationvibration patternにその値を設定します。

  16. もしoptions["timestamp"] 存在する場合は notificationtimestampにその値を設定します。そうでない場合は notificationtimestampfallbackTimestampを設定します。

  17. notificationrenotify preferenceoptions["renotify"]に設定します。

  18. notificationsilent preferenceoptions["silent"]に設定します。

  19. notificationrequire interaction preferenceoptions["requireInteraction"]に設定します。

  20. notificationactionsを« »に設定します。

  21. options["actions"]の各entryについて、 サポートされるアクションの最大数まで(余分なエントリーはスキップ):

    1. actionを新しい通知アクションとします。

    2. actionnameentry["action"]に設定します。

    3. actiontitleentry["title"]に設定します。

    4. もしentry["navigate"] 存在する場合、それをbaseURLパースし、失敗しない場合は actionnavigation URLにその値を設定します。 (失敗した場合、actionnavigation URLはnullのままです。)

    5. もしentry["icon"] 存在する場合、それをbaseURLパースし、失敗しない場合は actionicon URLにその値を設定します。(失敗した場合、actionicon URLはnullのままです。)

    6. actionnotificationactionsに追加します。

  22. notificationを返します。

2.1. ライフタイムとUI統合

ユーザーエージェントは、通知のリストを保持しなければなりません。これは、ゼロ個以上のリストとして 通知を管理します。

ユーザーエージェントは、非永続的通知に対して、作成後数秒でクローズ手順を実行するべきです。

ユーザーエージェントは、プラットフォームの「通知センター」(利用可能な場合)に非永続的通知を表示しないようにするべきです。

ユーザーエージェントは、永続的通知通知のリストから削除されるまで保持するべきです。

永続的通知は、 そのclose() メソッドがNotification オブジェクトのいずれかで呼び出される場合があります。

ユーザーエージェントは、永続的通知をプラットフォームの「通知センター」(利用可能な場合)に表示するべきです。

2.2. 権限統合

Notifications APIは、強力な機能として識別され、 名前 "notifications"で表されます。 [Permissions]

通知権限状態を取得するためには、以下の手順を実行します:

  1. permissionStateを"notifications"を使って 現在の権限状態を取得する結果とします。

  2. もしpermissionStateが"prompt"の場合、"default"を返します。

  3. permissionStateを返します。

2.3. 方向性

このセクションはHTMLのRenderingセクションで使用される用語と同等の内容で記述されています。[HTML]

ユーザーエージェントは、通知タイトル本文、および各アクションタイトルのUnicodeセマンティクスを尊重することが期待されています。表示時にはそれぞれが双方向アルゴリズムのルールP1、P2、P3に従い、LF文字(U+000A)の段落分割等も含め、独立した双方向アルゴリズム段落集合として扱われます。各段落について、 タイトル本文、および各アクションタイトルは、 通知directionが"auto"以外の場合、高レベルなP2およびP3の上書きとして機能します。[BIDI]

通知directionは、通知プラットフォームが並べて表示する場合、通知アクションがエンドユーザーへ表示される順序にも影響します。

2.4. 言語

通知languageは、 通知タイトル本文、 および各アクションタイトルの主な言語を指定します。その値は文字列です。空文字列は主な言語が不明であることを示します。それ以外の文字列は言語タグとして解釈されます。有効性や構文の正しさは強制されません。[BCP47]

開発者は有効な言語タグのみを使用することが推奨されています。

2.5. リソース

ある通知 notificationに対するフェッチ手順は以下の通りです:

  1. 通知プラットフォームが画像をサポートしている場合、フェッチ notificationimage URLimage URLが設定されている場合)。

    このリソースは <img> のようにフェッチする意図ですが、抽象化が必要です

    その後、並行して

    1. レスポンスを待つ。

    2. レスポンス内部レスポンスtypeが"default"の場合、そのリソースを画像としてデコードを試みる。

    3. 画像フォーマットがサポートされていれば、notificationimage resourceにデコード済みリソースを設定する。(そうでなければ notificationimage resourceを持たない。)

  2. 通知プラットフォームがアイコンをサポートしている場合、フェッチ notificationicon URLicon URLが設定されている場合)。

    このリソースは <img> のようにフェッチする意図ですが、抽象化が必要です

    その後、並行して

    1. レスポンスを待つ。

    2. レスポンス内部レスポンスtypeが"default"の場合、そのリソースを画像としてデコードを試みる。

    3. 画像フォーマットがサポートされていれば、notificationicon resourceにデコード済みリソースを設定する。(そうでなければ notificationicon resourceを持たない。)

  3. 通知プラットフォームがバッジをサポートしている場合、フェッチ notificationbadge URLbadge URLが設定されている場合)。

    このリソースは <img> のようにフェッチする意図ですが、抽象化が必要です

    その後、並行して

    1. レスポンスを待つ。

    2. レスポンス内部レスポンスtypeが"default"の場合、そのリソースを画像としてデコードを試みる。

    3. 画像フォーマットがサポートされていれば、notificationbadge resourceにデコード済みリソースを設定する。(そうでなければ notificationbadge resourceを持たない。)

  4. 通知プラットフォームがアクションおよびアクションアイコンをサポートしている場合、notificationactions内の各actionについて:icon URLがnullでない場合、フェッチ actionicon URL

    このリソースは <img> のようにフェッチする意図ですが、抽象化が必要です

    その後、並行して

    1. レスポンスを待つ。

    2. レスポンス内部レスポンスtypeが"default"の場合、そのリソースを画像としてデコードを試みる。

    3. 画像フォーマットがサポートされていれば、actionicon resourceにデコード済みリソースを設定する。(そうでなければ actionicon resourceはnullのまま。)

2.6. 通知の表示

指定された通知 notification通知表示手順は以下の通りです:

  1. notificationについてフェッチ手順を実行します。

  2. すべてのフェッチが完了し、notificationimage resourceicon resourcebadge resource (存在する場合)、および notificationactionsicon resources (存在する場合)がセットされるのを待ちます。

  3. shownをfalseとします。

  4. oldNotificationを、通知のリストの中から tagが空文字列でなく、 notificationtagと一致し、 originnotificationorigin同一オリジンであるもの(存在しない場合はnull)とします。

  5. oldNotificationがnullでない場合:

    1. oldNotificationに対してクローズイベント処理を行います。

    2. 通知プラットフォームが置換をサポートしている場合:

      1. 通知リストで oldNotificationnotificationに置き換えます。

      2. shownをtrueに設定します。

      通知プラットフォームは、ネイティブの置換をサポートすることが強く推奨されます。これはユーザー体験の向上につながります。

    3. それ以外の場合、通知リストから oldNotificationを削除します。

  6. shownがfalseの場合:

    1. 通知リストに notificationを追加します。

    2. デバイス上にnotificationを表示します(例:通知プラットフォームAPIを呼び出すなど)。

  7. shownがfalse、またはoldNotificationがnullでない場合で、 notificationrenotify preferenceがtrueであれば、 notificationについてアラート手順を実行します。

  8. notification非永続的通知の場合、 タスクをキューして Notification オブジェクト(notificationを表す)にshowイベントを 発火します。

2.7. 通知のアクティブ化

ユーザーが通知プラットフォームのアクティブ化をサポートしている場合、通知 notification またはその actions のいずれかがエンドユーザーによってアクティブ化されたとき、ユーザーエージェントは(他に指定がない限り)以下の手順を実行しなければなりません:

  1. actionをnullとします。

  2. エンドユーザーがnotificationactionsのいずれかをアクティブ化した場合、actionにその 通知アクションを設定します。

  3. navigationURLnotificationnavigation URLとします。

  4. actionがnullでない場合、navigationURLactionnotification action navigation URLに設定します。

    この仕様により、通知アクションnavigation URLがnullの場合は clickイベントにフォールスルーし、ウェブ開発者により柔軟性を提供します。

  5. navigationURLがnullでない場合:

    1. 実装定義の方法で次のいずれかを選択します:

      ユーザーエージェントはプラットフォームの慣習に合わせることが強く推奨されます。

    2. 終了します。

  6. notification永続的通知の場合:

    1. actionNameを空文字列とします。

    2. actionがnullでない場合、actionNameactionnameを設定します。

    3. notificationclickという名前でサービスワーカー通知イベントを発火します。notificationactionNameを指定します。
  7. それ以外の場合、タスクをキューして以下の手順を実行します:

    1. intoFocusNotification オブジェクト(notificationを表す)のclickイベントを 発火し、その cancelable 属性をtrueで初期化した結果とします。

      ユーザーエージェントは、focus()clickイベントリスナー内で動作するようにすることが推奨されます。

    2. intoFocusがtrueの場合、ユーザーエージェントは notificationの関連するブラウジングコンテキストのビューポートをフォーカスすべきです。

ウェブプラットフォーム全体で「activate」は意図的に「click」と誤称されています。

2.8. 通知のクローズ

通知が基盤となる通知プラットフォームまたはエンドユーザーによってクローズされた場合、その通知に対してクローズ手順を実行しなければなりません。

指定された通知 notificationクローズ手順は以下の通りです:

  1. 通知のリストnotification含まない場合、これらの手順を中止します。

  2. notificationに対してクローズイベント処理を行います。

  3. 通知のリストから notificationを削除します。

指定された通知 notificationに対してクローズイベント処理を行うには:

  1. notification永続的通知であり、かつ notificationがエンドユーザーによってクローズされた場合、"notificationclose"という名前でサービスワーカー通知イベントを発火します。notificationを指定します。

  2. notification非永続的通知の場合、 タスクをキューして Notification オブジェクト(notificationを表す)にcloseイベントを 発火します。

2.9. エンドユーザーへのアラート

指定された通知 notificationについてエンドユーザーにアラートを行うアラート手順は以下の通りです:

  1. notificationバイブレーションパターン(存在する場合)を用いて バイブレーションを実行します。

3. API

[Exposed=(Window,Worker)]
interface Notification : EventTarget {
  constructor(DOMString title, optional NotificationOptions options = {});

  static readonly attribute NotificationPermission permission;
  [Exposed=Window] static Promise<NotificationPermission> requestPermission(optional NotificationPermissionCallback deprecatedCallback);

  static readonly attribute unsigned long maxActions;

  attribute EventHandler onclick;
  attribute EventHandler onshow;
  attribute EventHandler onerror;
  attribute EventHandler onclose;

  readonly attribute DOMString title;
  readonly attribute NotificationDirection dir;
  readonly attribute DOMString lang;
  readonly attribute DOMString body;
  readonly attribute USVString navigate;
  readonly attribute DOMString tag;
  readonly attribute USVString image;
  readonly attribute USVString icon;
  readonly attribute USVString badge;
  [SameObject] readonly attribute FrozenArray<unsigned long> vibrate;
  readonly attribute EpochTimeStamp timestamp;
  readonly attribute boolean renotify;
  readonly attribute boolean? silent;
  readonly attribute boolean requireInteraction;
  [SameObject] readonly attribute any data;
  [SameObject] readonly attribute FrozenArray<NotificationAction> actions;

  undefined close();
};

dictionary NotificationOptions {
  NotificationDirection dir = "auto";
  DOMString lang = "";
  DOMString body = "";
  USVString navigate;
  DOMString tag = "";
  USVString image;
  USVString icon;
  USVString badge;
  VibratePattern vibrate;
  EpochTimeStamp timestamp;
  boolean renotify = false;
  boolean? silent = null;
  boolean requireInteraction = false;
  any data = null;
  sequence<NotificationAction> actions = [];
};

enum NotificationPermission {
  "default",
  "denied",
  "granted"
};

enum NotificationDirection {
  "auto",
  "ltr",
  "rtl"
};

dictionary NotificationAction {
  required DOMString action;
  required DOMString title;
  USVString navigate;
  USVString icon;
};

callback NotificationPermissionCallback = undefined (NotificationPermission permission);

非永続的通知は1つのNotification オブジェクトによって表され、Notificationコンストラクタで作成できます。

永続的通知は 0個以上の Notification オブジェクトによって表され、 showNotification() メソッドで作成できます。

3.1. ガベージコレクション

Notification オブジェクトは、通知リストが対応する通知含んでいて、 かつtypeclickshowcloseerror のいずれかであるイベントリスナーを持つ間は、ガベージコレクトされてはなりません。

3.2. コンストラクタ

new Notification(title, options) コンストラクタの手順は以下の通りです:

  1. this関連グローバルオブジェクトServiceWorkerGlobalScope オブジェクトの場合、 TypeErrorをスローします。

  2. options["actions"] が空でない場合、 TypeErrorをスローします。

    アクション永続的通知のみでサポートされます。

  3. notificationを、 設定オブジェクトで通知を作成する手順の titleoptionsthis関連設定オブジェクトを引数として実行した結果とします。

  4. thisnotificationと関連付けます。

  5. 並行して以下の手順を実行します:

    1. 通知権限状態を取得する結果が "granted"でない場合、 タスクをキューして thisにerrorイベントを発火し、 これらの手順を中止します。

    2. notificationについて通知表示手順を実行します。

3.3. 静的メンバー

静的permissionゲッターの手順は、通知の権限状態を取得するの結果を返します。

標準を編集する場合は、上記の内容をコピーしないでください。同期的な権限は同期I/Oと同様に、良くない考え方です。

開発者はPermissionsのquery() メソッドの利用が推奨されます。[Permissions]

const permission = await navigator.permissions.query({name: "notifications"});
if (permission.state === "granted") {
   // APIの利用権限があります…
}

静的 requestPermission(deprecatedCallback) メソッドの手順は以下の通りです:

  1. global現在のグローバルオブジェクトとします。

  2. promise新しいPromiseとして、this関連Realmで生成します。

  3. 並行して以下の手順を実行します:

    1. permissionState"notifications"の利用権限を要求する結果とします。

    2. DOM操作タスクソース上でglobalに対してグローバルタスクをキューし、以下の手順を実行します:

      1. deprecatedCallbackが与えられていれば、コールバック関数を呼び出す (引数は« permissionState »と"report")。

      2. promiseをpermissionStateで解決します。

  4. promiseを返します。

通知は、現時点で唯一エンドユーザーに最初から尋ねることが理にかなうAPIです。他のAPI仕様はこのパターンを使うべきではなく、 より適切な代替案を採用してください。

静的maxActionsゲッターの手順は、 サポートされるアクションの最大数を返します。

3.4. オブジェクトメンバー

以下は、イベントハンドラ(および対応する イベントハンドライベントタイプ)であり、 Notification オブジェクトの属性としてサポートされなければなりません。

イベントハンドラ イベントハンドライベントタイプ
onclick click
onshow show
onerror error
onclose close

title ゲッターの手順は、 thisnotificationtitleを返すことです。

dir ゲッターの手順は、 thisnotificationdirectionを返すことです。

lang ゲッターの手順は、 thisnotificationlanguageを返すことです。

body ゲッターの手順は、 thisnotificationbodyを返すことです。

navigate ゲッターの手順は以下の通りです:

  1. thisnotificationnavigation URL が null なら、空文字列を返すこと。

  2. thisnotificationnavigation URLシリアライズして返すこと。

tag ゲッターの手順は、 thisnotificationtagを返すことです。

image ゲッターの手順は以下の通りです:

  1. thisnotificationimage URLがなければ、 空文字列を返すこと。

  2. thisnotificationimage URLシリアライズして返すこと。

icon ゲッターの手順は以下の通りです:

  1. thisnotificationicon URLがなければ、空文字列を返すこと。

  2. thisnotificationicon URLシリアライズして返すこと。

badge ゲッターの手順は以下の通りです:

  1. thisnotificationbadge URLがなければ、空文字列を返すこと。

  2. thisnotificationbadge URLシリアライズして返すこと。

vibrate ゲッターの手順は、 thisnotificationvibration patternを返すことです。

timestamp ゲッターの手順は、 thisnotificationtimestampを返すことです。

renotify ゲッターの手順は、 thisnotificationrenotify preferenceを返すことです。

silent ゲッターの手順は、 thisnotificationsilent preferenceを返すことです。

requireInteraction ゲッターの手順は、 thisnotificationrequire interaction preferenceを返すことです。

data ゲッターの手順は、 StructuredDeserialize(thisnotificationdata, thisrelevant Realm)の結果を返すこと。もし例外がスローされた場合は null を返すこと。

actions ゲッターの手順は以下の通りです:

  1. frozenActionsNotificationAction型の空リストとする。

  2. thisnotificationactionsの各entryについて:

    1. actionを新しい NotificationAction とする。

    2. action["action"] に entryname を設定する。

    3. action["title"] に entrytitle を設定する。

    4. entrynavigation URL が null でなければ、 action["navigate"] に entrynavigation URLシリアライズして設定する。

    5. entryicon URL が null でなければ、 action["icon"] に entryicon URLシリアライズして設定する。

    6. Object.freezeaction に呼び出して、 スクリプトによる偶発的な変更を防ぐこと。

    7. actionfrozenActions に追加する。

  3. frozenActions から凍結配列を作成した結果を返すこと。

3.5.

3.5.1. ページからイベントを利用する

非永続的Notification オブジェクトはライフサイクルの中でイベントを発行し、開発者はそれを使って 望ましい動作を生成できます。

エンドユーザーが通知をアクティブ化したとき、clickイベントが発行されます。

var not = new Notification("Gebrünn Gebrünn by Paul Kalkbrenner", { icon: "newsong.svg", tag: "song" });
not.onclick = function() { displaySong(this); };

3.5.2. サービスワーカーからアクションを利用する

永続的通知notificationclickイベントをServiceWorkerGlobalScope上で発火します。

次の例ではサービスワーカーが「Archive」アクションを持つ通知を1つ表示し、エンドユーザーが 通知からこの一般的なタスク(例えば通知プラットフォームが通知上にボタンを表示する)を ウェブサイトを開かずに実行できるようにします。エンドユーザーは通知本体をアクティブ化して 受信箱を開くこともできます。

self.registration.showNotification("New mail from Alice", {
  actions: [{action: 'archive', title: "Archive"}]
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  if (event.action === 'archive') {
    silentlyArchiveEmail();
  } else {
    clients.openWindow("/inbox");
  }
}, false);

3.5.3. tagメンバーによる複数インスタンスの利用例

ウェブアプリケーションは、エンドユーザーが複数のブラウザタブでメールアプリを開くなど、 しばしば複数インスタンスで同時に動作します。デスクトップは共有リソースなので、 Notifications APIはtagメンバーを使って これらのインスタンスが簡単に連携できる仕組みを提供します。

同じ概念イベントを表す通知は同じタグでマークでき、両方が表示される場合でも エンドユーザーは1つの通知だけを受け取ります。

Instance 1                                   | Instance 2
                                             |
// Instance notices there is new mail.       |
new Notification("New mail from John Doe",   |
                 { tag: 'message1' });       |
                                             |
                                             |  // Slightly later, this instance notices
                                             |  // there is new mail.
                                             |  new Notification("New mail from John Doe",
                                             |                   { tag: 'message1' });

ユーザーエージェントがここで定義されたアルゴリズムに従う場合、この状況の結果は1つだけの "New mail from John Doe"通知になります。

3.5.4. 単一インスタンスでtagメンバーを利用する

tagメンバーはアプリケーションの単一インスタンスでも、通知を最新状態に保つために利用できます。

例えば、AliceがBobとチャットアプリを使っていて、Aliceが離席中にBobが複数メッセージを 送った場合、アプリケーションはAliceが各メッセージごとにデスクトップ通知を受け取らないようにしたいかもしれません。

// Bob says "Hi"
new Notification("Bob: Hi", { tag: 'chat_Bob' });

// Bob says "Are you free this afternoon?"
new Notification("Bob: Hi / Are you free this afternoon?", { tag: 'chat_Bob' });

この状況の結果は1つだけの通知となり、2つ目の通知が同じタグを持つ最初の通知を 置き換えます。通知がキュー(先入れ先出し)されるプラットフォームでは、 タグを使うことで通知のキュー内位置も保てます。最新通知が先頭に表示されるプラットフォームでは、 close() メソッドを利用することで同様の結果が得られます。

4. サービスワーカーAPI

dictionary GetNotificationOptions {
  DOMString tag = "";
};

partial interface ServiceWorkerRegistration {
  Promise<undefined> showNotification(DOMString title, optional NotificationOptions options = {});
  Promise<sequence<Notification>> getNotifications(optional GetNotificationOptions filter = {});
};

[Exposed=ServiceWorker]
interface NotificationEvent : ExtendableEvent {
  constructor(DOMString type, NotificationEventInit eventInitDict);

  readonly attribute Notification notification;
  readonly attribute DOMString action;
};

dictionary NotificationEventInit : ExtendableEventInit {
  required Notification notification;
  DOMString action = "";
};

partial interface ServiceWorkerGlobalScope {
  attribute EventHandler onnotificationclick;
  attribute EventHandler onnotificationclose;
};

service worker registrationには、 showNotification()が正常に呼び出されたかboolean型)が関連付けられており、初期値はfalseです。

これはPush API現行標準のためのインフラです。[PUSH-API]

showNotification(title, options) メソッドの手順は以下の通りです:

  1. globalthis関連グローバルオブジェクトとします。

  2. promise新しいPromiseとして、this関連Realmで生成します。

  3. thisactive workerがnullなら、 promiseをTypeErrorでrejectし、promiseを返します。

  4. notification設定オブジェクトで通知を作成する手順で title, options, this関連設定オブジェクトを渡して作成した結果とします。例外が発生した場合は promiseをその例外でrejectし、promiseを返します。

  5. notificationservice worker registrationthisに設定します。

  6. 並行して以下の手順を実行します:

    1. 通知権限状態を取得する結果が "granted"でない場合、 DOM操作タスクソース上でglobalに対してグローバルタスクをキューし、 promiseをTypeErrorでreject し、これらの手順を中止します。

    2. notificationについて通知表示手順を実行します。

    3. notificationservice worker registrationshowNotification()が正常に呼び出されたか をtrueにします。

    4. DOM操作タスクソース上でglobalに対してグローバルタスクをキューし、 promiseをundefinedでresolve します。

  7. promiseを返します。

getNotifications(filter) メソッドの手順は以下の通りです:

  1. globalthis関連グローバルオブジェクトとします。

  2. realmthis関連Realmとします。

  3. originthis関連設定オブジェクトoriginとします。

  4. promise新しいPromiseとしてrealmで生成します。

  5. 並行して以下の手順を実行します:

    1. tagfilter["tag"]とします。

    2. notificationsを、リストとして、 通知のリスト内で originorigin同一オリジンであり、 service worker registrationthisであるもの、 かつtagが空文字列でない場合はtagtagであるもの のすべての通知とします。

    3. DOM操作タスクソース上でglobalに対してグローバルタスクをキューし、以下の手順を実行します:

      1. objectsリストとして初期化します。

      2. notificationsの各notificationについて、作成順に realmでその通知を表す新しいNotification オブジェクトを作成し、objectsに追加します。

      3. promiseをobjectsでresolveします。

  6. promiseを返します。

このメソッドは、新しいNotification オブジェクトを0個以上返します。返されたオブジェクトは、すでに存在しているNotificationオブジェクトが表すものと同じ 基礎となる通知を表す場合があります。


サービスワーカー通知イベントを発火するには、名前namenotification notification、オプションの文字列action(デフォルトは空文字列)を受け取り、Fire Functional EventnameNotificationEventnotificationservice worker registration、および次の初期化で実行します:

notification
新しいNotificationオブジェクトでnotificationを表す。
action
action

notificationゲッターの手順は、初期化時の値を返すことです。

actionゲッターの手順は、初期化時の値を返すことです。

次のものは、イベントハンドラ(および対応する イベントハンドライベントタイプ)であり、 ServiceWorkerGlobalScope オブジェクトの属性としてサポートされなければなりません:

イベントハンドラ イベントハンドライベントタイプ
onnotificationclick notificationclick
onnotificationclose notificationclose

謝辞

以下の方々に感謝します: Addison Phillips, Aharon (Vladimir) Lanin, Alex Russell, Anssi Kostiainen, Arkadiusz Michalski, Boris Zbarsky, Brady Eidson, David Håsäther, Doug Turner, Drew Wilson, Ehsan Akhgari, Frederick Hirsch, Ian Hickson, Jake Archibald, James Graham, John Mellor, Jon Lee, Jonas Sicking, Kagami Sascha Rosylight, Michael Cooper, Michael Henretty, Michael™ Smith, Michael van Ouwerkerk, Mike Taylor, Nicolás Satragno, Olli Pettay, Peter Beverloo, Philip Jägenstedt, Reuben Morais, Rich Tibbett, Robert Bindar, 박상현 (Sanghyun Park), Simon Pieters, Theresa O’Connor, timeless, および triple-underscore の皆さん、素晴らしい貢献に感謝します。

この現行標準は Anne van Kesteren (Apple, annevk@annevk.nl) によって執筆されています。以前のバージョンは John Gregg (Google, johnnyg@google.com) によって執筆されました。

知的財産権

Copyright © WHATWG (Apple, Google, Mozilla, Microsoft)。この作品は クリエイティブ・コモンズ 表示 4.0 国際ライセンス の下でライセンスされています。その一部がソースコードに組み込まれている場合は、その部分は BSD 3-Clause License の下でライセンスされます。

これは現行標準です。 特許レビュー版を希望される方は 現行標準レビュー草案をご覧ください。

索引

この仕様書で定義されている用語

参考文献によって定義されている用語

参考文献

規範参考文献

[BCP47]
A. Phillips, Ed.; M. Davis, Ed.. Tags for Identifying Languages. 2009年9月. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc5646
[BIDI]
Manish Goregaokar मनीष गोरेगांवकर; Robin Leroy. Unicode Bidirectional Algorithm. 2024年9月2日. Unicode Standard Annex #9. URL: https://www.unicode.org/reports/tr9/tr9-50.html
[DOM]
Anne van Kesteren. DOM Standard. 現行標準. URL: https://dom.spec.whatwg.org/
[FETCH]
Anne van Kesteren. Fetch Standard. 現行標準. URL: https://fetch.spec.whatwg.org/
[HR-TIME]
Yoav Weiss. High Resolution Time. URL: https://w3c.github.io/hr-time/
[HTML]
Anne van Kesteren; et al. HTML Standard. 現行標準. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. 現行標準. URL: https://infra.spec.whatwg.org/
[Permissions]
Marcos Caceres; Mike Taylor. Permissions. URL: https://w3c.github.io/permissions/
[SERVICE-WORKERS]
Yoshisato Yanagisawa; Monica CHINTALA. Service Workers. URL: https://w3c.github.io/ServiceWorker/
[URL]
Anne van Kesteren. URL Standard. 現行標準. URL: https://url.spec.whatwg.org/
[VIBRATION]
Anssi Kostiainen. Vibration API. URL: https://w3c.github.io/vibration/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. 現行標準. URL: https://webidl.spec.whatwg.org/

参考情報

[PUSH-API]
Peter Beverloo; Martin Thomson; Marcos Caceres. Push API. URL: https://w3c.github.io/push-api/

IDL索引

[Exposed=(Window,Worker)]
interface Notification : EventTarget {
  constructor(DOMString title, optional NotificationOptions options = {});

  static readonly attribute NotificationPermission permission;
  [Exposed=Window] static Promise<NotificationPermission> requestPermission(optional NotificationPermissionCallback deprecatedCallback);

  static readonly attribute unsigned long maxActions;

  attribute EventHandler onclick;
  attribute EventHandler onshow;
  attribute EventHandler onerror;
  attribute EventHandler onclose;

  readonly attribute DOMString title;
  readonly attribute NotificationDirection dir;
  readonly attribute DOMString lang;
  readonly attribute DOMString body;
  readonly attribute USVString navigate;
  readonly attribute DOMString tag;
  readonly attribute USVString image;
  readonly attribute USVString icon;
  readonly attribute USVString badge;
  [SameObject] readonly attribute FrozenArray<unsigned long> vibrate;
  readonly attribute EpochTimeStamp timestamp;
  readonly attribute boolean renotify;
  readonly attribute boolean? silent;
  readonly attribute boolean requireInteraction;
  [SameObject] readonly attribute any data;
  [SameObject] readonly attribute FrozenArray<NotificationAction> actions;

  undefined close();
};

dictionary NotificationOptions {
  NotificationDirection dir = "auto";
  DOMString lang = "";
  DOMString body = "";
  USVString navigate;
  DOMString tag = "";
  USVString image;
  USVString icon;
  USVString badge;
  VibratePattern vibrate;
  EpochTimeStamp timestamp;
  boolean renotify = false;
  boolean? silent = null;
  boolean requireInteraction = false;
  any data = null;
  sequence<NotificationAction> actions = [];
};

enum NotificationPermission {
  "default",
  "denied",
  "granted"
};

enum NotificationDirection {
  "auto",
  "ltr",
  "rtl"
};

dictionary NotificationAction {
  required DOMString action;
  required DOMString title;
  USVString navigate;
  USVString icon;
};

callback NotificationPermissionCallback = undefined (NotificationPermission permission);

dictionary GetNotificationOptions {
  DOMString tag = "";
};

partial interface ServiceWorkerRegistration {
  Promise<undefined> showNotification(DOMString title, optional NotificationOptions options = {});
  Promise<sequence<Notification>> getNotifications(optional GetNotificationOptions filter = {});
};

[Exposed=ServiceWorker]
interface NotificationEvent : ExtendableEvent {
  constructor(DOMString type, NotificationEventInit eventInitDict);

  readonly attribute Notification notification;
  readonly attribute DOMString action;
};

dictionary NotificationEventInit : ExtendableEventInit {
  required Notification notification;
  DOMString action = "";
};

partial interface ServiceWorkerGlobalScope {
  attribute EventHandler onnotificationclick;
  attribute EventHandler onnotificationclose;
};

MDN

Notification/Notification

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for AndroidNoneAndroid WebView?Samsung Internet?Opera Mobile?
MDN

Notification/actions

In only one current engine.

FirefoxNoneSafariNoneChrome53+
Opera39+Edge79+
Edge (Legacy)18IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?

NotificationEvent/action

Firefox44+SafariNoneChrome48+
OperaNoneEdge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera MobileNone
MDN

Notification/badge

In only one current engine.

FirefoxNoneSafariNoneChrome53+
Opera39+Edge79+
Edge (Legacy)18IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/body

In all current engines.

Firefox26+Safari11+Chrome33+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/click_event

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS SafariNoneChrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/close

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/close_event

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS SafariNoneChrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/data

In all current engines.

Firefox34+Safari16+Chrome44+
Opera?Edge79+
Edge (Legacy)16+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/dir

In all current engines.

Firefox26+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/error_event

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS SafariNoneChrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/icon

In all current engines.

Firefox26+Safari11+Chrome33+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/image

In only one current engine.

FirefoxNoneSafariNoneChrome56+
Opera?Edge79+
Edge (Legacy)18IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/lang

In all current engines.

Firefox26+Safari11+Chrome33+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/maxActions_static

In only one current engine.

FirefoxNoneSafariNoneChrome48+
Opera?Edge79+
Edge (Legacy)18IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/permission_static

In all current engines.

Firefox22+Safari7+Chrome32+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/renotify

In only one current engine.

FirefoxNoneSafariNoneChrome50+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/requestPermission_static

In all current engines.

Firefox22+Safari15+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android22+iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/requireInteraction

In only one current engine.

FirefoxNoneSafariNoneChrome47+
Opera?Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/show_event

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS SafariNoneChrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/silent

FirefoxNoneSafari17+Chrome43+
Opera?Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/tag

In all current engines.

Firefox26+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS SafariNoneChrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/timestamp

In only one current engine.

FirefoxNoneSafariNoneChrome50+
Opera?Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/title

In all current engines.

Firefox26+Safari11+Chrome33+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android42+Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

Notification/vibrate

In only one current engine.

FirefoxNoneSafariNoneChrome53+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android53+Android WebViewNoneSamsung Internet6.0+Opera Mobile41+
MDN

Notification

In all current engines.

Firefox22+Safari7+Chrome20+
Opera23+Edge79+
Edge (Legacy)14+IENone
Firefox for Android?iOS Safari16.4+Chrome for AndroidNoneAndroid WebViewNoneSamsung InternetNoneOpera MobileNone
MDN

NotificationEvent/NotificationEvent

In all current engines.

Firefox44+SafariNoneChrome42+
Opera37+Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile37+
MDN

NotificationEvent/notification

Firefox44+SafariNoneChrome42+
Opera37+Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile37+
MDN

NotificationEvent

In all current engines.

Firefox44+SafariNoneChrome42+
Opera37+Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile37+
MDN

ServiceWorkerGlobalScope/notificationclick_event

Firefox44+SafariNoneChrome40+
Opera24+Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS SafariNoneChrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ServiceWorkerGlobalScope/notificationclick_event

Firefox44+SafariNoneChrome40+
Opera24+Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS SafariNoneChrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ServiceWorkerGlobalScope/notificationclose_event

Firefox44+SafariNoneChrome50+
Opera34+Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS SafariNoneChrome for Android?Android WebView?Samsung Internet?Opera Mobile34+
MDN

ServiceWorkerRegistration/getNotifications

In all current engines.

Firefox44+SafariNoneChrome40+
Opera?Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?
MDN

ServiceWorkerRegistration/showNotification

In all current engines.

Firefox44+SafariNoneChrome42+
Opera?Edge79+
Edge (Legacy)17+IENone
Firefox for Android?iOS Safari16.4+Chrome for Android?Android WebViewNoneSamsung Internet?Opera Mobile?