Badging API

Unofficial Draft 20 December 2022

More details about this document
This version:
https://www.w3.org/TR/unofficial-badging-20221220/ https://www.w3.org/TR/unofficial-badging-20230324/
Latest published version:
none
Latest editor's draft:
https://w3c.github.io/badging/
History:
Commit history
Editor:
Marcos Cáceres ( Apple Inc. )
Former editors:
Matt Giuca ( Google Inc. ) Former editor: - Until
Jay Harris ( Google Inc. ) - Until
Feedback:
GitHub w3c/badging ( pull requests , new issue , open issues )

Abstract

This specification defines an API allowing web pages and that allows installed web applications to set a badge on the document, or an application-wide application badge, which is usually shown in an operating-system-specific place associated with alongside the application (such as application's icon on the shelf or device's home screen), for the purpose of notifying the user when the state of the page screen or application has changed (e.g., when new messages have arrived), without showing a more heavyweight notification. dock.

Status of This Document

This is a preview

Do not attempt to implement this version of the specification. Do not reference this version as authoritative in any way. Instead, see https://w3c.github.io/badging/ for the Editor's draft.

This document is a draft of a potential specification. It has no official standing of any kind and does not represent the support or consensus of any standards organization.

This is an early draft of the Badging API spec. a work in progress.

1. Usage examples

This section is non-normative.

The following example shows how an email application might set a badge showing the unread count associated with the current document, which is updated whenever the client polls for mail from the server.
Example 1 : Showing unread count for this document { navigator.setClientBadge(getUnreadCount()); } The next example shows how a game might show when it is the player's turn. Again, this associates the badge with on the current document. Example 2 app icon
async function updateMailBadge() {  // Check if the API is supported.  if (!navigator.setAppBadge) return;
  const unreadCount = await getUnreadMailCount();
:
Showing
ready
status
for
this
document
  {
   (playerTurnId === localPlayerId)
    navigator.setClientBadge();
  
    navigator.clearClientBadge();

  // Try to set the app badge.
  try {
    await navigator.setAppBadge(unreadCount);
  } catch (e) {
    // The badge is not supported, or the user has prevented the app    // from setting a badge.
  }

}

A separate set of methods set the badge on the installed web application , if any, whose navigation scope this document is within. The badge might show up on the application's icon in the operating system shelf. These examples work the same as above, except that the badge has global scope (if system. If multiple documents API calls within the same application set or clear a badge, the most recent one takes effect), effect, and can may continue being seen even after the last document closes. an application is closed.

Example 3 2 : Showing unread count ready status on the app icon { navigator.setAppBadge(getUnreadCount());
async function showPlayerTurn(playerTurnId) {
  if (playerTurnId === localPlayerId)
    await navigator.setAppBadge();
  else
    await navigator.clearAppBadge();
}

On some operating systems setting a badge can require permission from the user. In this case, a developer need to query the " notifications " permissions status before setting a badge. If the permission is not granted, the developer will need to prompt for permission via the Notification . requestPermission () .

Example 4 3 : Showing ready status on the app icon Checking for permission { (playerTurnId === localPlayerId) navigator.setAppBadge(); navigator.clearAppBadge();
async function checkPermission() {
  permission = await navigator.permissions.query({
    name: "notifications",
  });
  const button = document.getElementById("permission-button");  if (permission.state === "prompt") {    // Prompt the user to grant permission.
    button.hidden = false;
    button.addEventListener("click", async () => {
      await Notification.requestPermission();
      checkPermission();
    }, { once: true });
    return;
  }
  button.hidden = true;

}

To show a badge on both the document(s) and app icon(s), use both APIs together.

2. Badge model Model

A badge may be is intended as a mechanism for installed web applications to notify the user that there is some new activity that might require their attention, or as a way of indicating a small amount of information, such as an unread count.

A badge can have one of the following values: values :

The special value nothing , which indicates "nothing" :
Indicates that there is no badge currently set. set .
The special value flag , which indicates "flag" :
Indicates that the badge is set, set , but contains no specific data. An unsigned long long value.
A number value:
Indicates that the badge is set value, which MUST NOT be 0. to a numerical value greater than 0 .

Each document and each An installed web application is has an associated with a badge value, , which is initialized to nothing "nothing" .

The user agent MAY reset (re) set an application's badge to nothing "nothing" at its discretion (for example, when the following system is restarted). If a badge is nothing , it is said to be " cleared ". Otherwise, it is said to be " set ". conventions).

3. Badge display Displaying a badge

When a document's the application's badge is set , if the document's browsing context is a top-level browsing context , , the user agent or operating system SHOULD display the document's application's badge value alongside the other identifying information for that document primary iconic representation of the application in the user's operating system (for example, as a small overlay on top of the document's application's icon or near its title). Note The user agent is not expected to display a badge associated with a document that is not on the home screen on a top-level browsing context , although it is allowed to. device).

A user agent does not need MAY require express permission from the user to store set the badge for badge. When a non-top-level browsing context if user agent requires such permission , it does not intend SHOULD tie the permission grant to display it. the " notifications " permission.

When the application's badge is set to "flag" , the user agent or operating system SHOULD display the application's an indicator with a non-specific symbol (for example, a colored circle).

When a badge alongside any symbolic representations of the application in 's value is set to "nothing" , the user's user agent or operating system (for example, as a small overlay on top of SHOULD clear the application's icon). badge by no longer displaying it.

If When the badge is set to special value flag a number , the user agent or operating system:

4. Extensions to the Navigator and WorkerNavigator interfaces

The Navigator and WorkerNavigator interfaces are extended with methods for setting and clearing both the document and application badge indicators from documents and service workers, respectively. ] partial interface }; []
WebIDL[SecureContext]
interface mixin NavigatorBadge {
  

  Promise<undefined> setAppBadge(
    optional [EnforceRange] unsigned long long contents
  );

  Promise<undefined> clearAppBadge();
};
Navigator includes NavigatorBadge;

WorkerNavigator

includes


NavigatorBadge


;


User agents that never display document badges SHOULD NOT expose the setClientBadge () and clearClientBadge () methods. Similarly, user agents that never display application badges SHOULD NOT expose the setAppBadge include () and clearAppBadge NavigatorBadge () methods. .

Raised by @marcoscaceres on #57 . I could go either way on this. The reason it's currently specified as "fire and forget" and always resolve the promise is that the API is a "best effort". Especially for the app version of the API, you could store the badge state locally, then try to set the badge in 3 places in the OS, some of which succeed and others of which fail. There's no reasonable way to communicate the partial success back to the user. So it's currently specified as "always report success to the user, even if it failed at the OS level". We could change this.

4.1 setClientBadge() setAppBadge() method

When the setClientBadge setAppBadge () method is called with argument contents : Return a promise resolved with undefined, and in parallel : Let document be this 's relevant global object 's associated Document . If contents is omitted, set called, the badge associated with document to flag . Else, if contents is 0, user agent MUST set the application badge associated with document of this to nothing . Else, set value of the badge associated with document to contents . argument.

4.2 clearClientBadge() clearAppBadge() method

When the clearClientBadge clearAppBadge () method is called: Let document be this 's relevant global object associated document . Return a promise resolved with undefined and In parallel , called, the user agent MUST set the application badge associated with document of this to nothing . 0.

4.3 5. setAppBadge() method Setting the application badge

When To set the application badge of platform object context to an optional setAppBadge unsigned long long () method is called with argument contents : value:

  1. Let global be this context 's relevant global object .
  2. If global is a Window object, then:
    1. Let document be global 's associated Document is null, and the environment settings object .
    2. If document is not a service worker client fully active , return a promise rejected with a " NotSupportedError " DOMException InvalidStateError .
  3. Otherwise, return Let promise be a new promise resolved with undefined, and .
  4. in In parallel :
    1. Let result be the result of determining the matching applications on If this 's relevant settings object . For each app in result : If contents is omitted, set the badge associated with app to flag . Else, if contents is 0, set the badge associated with app to nothing . Else, set the badge associated with app to contents . 4.4 clearAppBadge() method When the clearAppBadge 's origin () method is called: Let global be not same origin with this 's relevant global object . If global 's associated Document is null, and the environment settings object is not a service worker client 's top-level origin , return queue a global task on the DOM manipulation task source given global to reject promise rejected with a " NotSupportedError SecurityError " DOMException . and terminate this algorithm.
    2. Otherwise, return a promise resolved with If the user agent undefined, and in parallel : requires express permission to set the application badge, then:
      1. Let result permissionState be the result of determining getting the matching applications current permission state on this with " notifications 's relevant settings object . ".
      2. Set the badge associated with each application in result If permissionState to nothing . 4.5 Determining the set of matching applications Note This algorithm is used to decide which app(s) receive a badge when the not " setAppBadge granted () method is called from either a document or service worker context. If called from a document context, the badge is applied to at most one application: the one with the most specific scope whose scope encloses this document URL. If called from a service worker context, the badge is applied to all applications whose scope sits within the service worker's scope. The steps for determining the matching applications takes an environment settings object environment that either has ", queue a global object task with an associated Document , or is a service worker client , and returns a set on the user interaction task source of installed web applications : If environment has a given global object to reject promise with an associated a Document NotAllowedError that is not null: and terminate this algorithm.
    3. Let apps Switching on contents , if it happens to be the set of installed web applications case that:
      contents was not passed:
      Set such that document badge to "flag" .
      contents 's URL is within scope of the application's manifest. (Order is not important.) Remove 0:
      Set all elements of apps badge other than the one with the longest (i.e., most specific) navigation scope to "nothing" . Return apps
      contents :
      Set badge to contents .
    4. Otherwise ( environment is Queue a service worker client global task ): Return on the set of installed web applications whose navigation scope is within scope DOM manipulation task source of environment given global 's containing service worker registration to resolve 's scope url . (Order is not important.) promise with undefined .
  5. Return promise .

5. 6. Security and privacy considerations

This section is non-normative.

The API is write-only by design. There is no way for a site to read back the value of a badge that was previously set, to ensure that the application badge cannot be used as a storage or fingerprinting mechanism.

The user agent or operating system MAY clear a badge at its discretion, and to follow any system conventions (for example, when the system is reset).

Issue 44 68 : Badge permission... Rate limiting the ability to set a badge

For installed apps, showing badges makes sense, because of the song-and-dance the users have Raised by @grorg on webkit-dev :

I'd also like to go through see some specification text describing how the browser should ignore multiple set/clear operations executed in rapid succession (e.g. to install create a web apps. However, I wonder if we need to gate blinking badge) - maybe the API using limit is one badge operation per minute or something?

We should address this; it might be a permission recommendation rather than a requirement, since it relates to mitigate tabs unnecessarily drawing the user's attention? UI of the user agent.

I'd like to see some sort of "eventual consistency" guarantee which says that the final value you write to the badge will eventually be the one displayed to the user. This could potentially prevents a situation where you set "3" then 10 seconds later set "12", and due to rate limiting, the "12" never gets set, so the user just sees "3" forever. Instead, the rule should be handled at "If the UI layer... just putting this here for discussion. hasn't been updated in > N seconds, update it to the new value. Otherwise, set a timer to update the UI to the new value in N - (however long it has been since the last update) seconds."

6. 7. Accessibility considerations

This section is non-normative.

Issue 24 : Add accessibility section

If the browser is in the control of presenting the badge, it should be possible to define some accessibility guidelines.

7. 8. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MAY , MUST NOT , SHOULD , and SHOULD NOT in this document are to be interpreted as described in BCP 14 [ RFC2119 ] [ RFC8174 ] when, and only when, they appear in all capitals, as shown here.

A. References

A.1 Normative references

[appmanifest]
Web Application Manifest . Marcos Caceres; Kenneth Christiansen; Matt Giuca; Aaron Gustafson; Daniel Murphy; Anssi Kostiainen. W3C. 20 December 2022. 25 January 2023. W3C Working Draft. URL: https://www.w3.org/TR/appmanifest/ [dom] DOM Standard . Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/
[html]
HTML Standard . Anne van Kesteren; Domenic Denicola; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[infra]
Infra Standard . Anne van Kesteren; Domenic Denicola. WHATWG. Living Standard. URL: https://infra.spec.whatwg.org/ [ltli]
[notifications]
Language Tags and Locale Identifiers for the World Wide Web Notifications API Standard . Addison Phillips. Anne van Kesteren. WHATWG. Living Standard. URL: https://notifications.spec.whatwg.org/
[permissions]
Permissions . Marcos Caceres; Mike Taylor. W3C. 7 October 2020. 20 December 2022. W3C Working Draft. URL: https://www.w3.org/TR/ltli/ https://www.w3.org/TR/permissions/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels . S. Bradner. IETF. March 1997. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc2119
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words . B. Leiba. IETF. May 2017. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc8174 [service-workers] Service Workers . Jake Archibald; Marijn Kruisselbrink. W3C. 12 July 2022. W3C Candidate Recommendation. URL: https://www.w3.org/TR/service-workers/
[webidl] [WEBIDL]
Web IDL Standard . Edgar Chen; Timothy Gu. WHATWG. Living Standard. URL: https://webidl.spec.whatwg.org/