Skip to main content




Notification triggers allow you to schedule local notifications that don't require a network connection, making them ideal for use cases like calendar apps.


Updated

El desarrollo de Notification Triggers API, parte de Google
capabilities project, is currently on hold. This post will be updated as implementation progresses.

What are notification triggers?

Los desarrolladores Web pueden mostrar notificaciones mediante el
Web Notifications API. This function is often used with API push para informar al Username de información urgente, como noticias de última hora o mensajes recibidos. Las notificaciones se muestran ejecutando JavaScript en el dispositivo del usuario.

The problem with the Push API is that it is not reliable to trigger notifications that has to will be displayed when a particular condition is met, such as time or location. An example of time-based condition is a calendar notification that reminds you of an important meeting with your boss at 2 pm An example of location-based condition es una notificación que le recuerda que debe comprar leche cuando ingresa a las inmediaciones de su supermercado. La conectividad de red o las funciones de conservación de la batería, como el modo dormido, pueden retrasar la entrega de push notifications.

Notification triggers solve this problem by allowing you to schedule notifications with their activation condition in advance, so that the operating system delivers the notification at the right time even if there is no network connectivity or the device is in battery saving mode.

For now, Chrome only supports time-based triggers. Additional triggers, such as location-based triggers, may be added in the future, depending on developer demand.

Use cases

Calendar applications can use time-based notification triggers to remind the user of upcoming meetings. The default notification scheme for a calendar app might be to show a first notification one hour before a meeting and then another more urgent notification five minutes before.

Una cadena de televisión puede recordar a los usuarios que su programa de televisión favorito está a punto de comenzar o que está a punto de comenzar una transmisión en vivo de una conference.

Los sitios de conversion de zona horaria pueden utilizar activadores de notificación basados ​​en el tiempo para permitir a sus usuarios programar alarmas para conferencias telefónicas o videollamadas.

Actual state

He passed Condition
1. Create an explainer To complete
2. Create initial draft specification Not started
3. Collect feedback and repeat the design In progress
4. Proof of origin To complete
5. Launch Not started

A proof of origin for the feature, which gave developers the opportunity to test the proposed API, ran from Chrome 80 to 83 and ended on July 29, 2020. Unfortunately, we did not receive many registrations and the feedback we received was not strong. For now, we have decided to put the API on hold until further notice and not extend the proof of origin. The feature will continue to be available behind the experimental web platform feature mark for developers to experiment with the API. Given future developer interest or new use cases, we will reconsider the API and resume efforts to standardize it.

How to use notification triggers

Enabling via chrome: // flags

To experiment with the Claims Triggers API locally, without a source test token, enable the
#enable-experimental-web-platform-features flag on chrome://flags.

Feature detection

Puede averiguar si el browser es compatible con los activadores de notificación comprobando la existencia del
showTrigger property:

if ("showTrigger" in Notification.prototype) {
}

Schedule a notification

Scheduling a notification is similar to displaying a regular push notification, except that you must pass a showTrigger property condition with a TimestampTrigger object as the claim value options object.

const createScheduledNotification = async (tag, title, timestamp) => {
const registration = await navigator.serviceWorker.getRegistration();
registration.showNotification(title, {
tag: tag,
body: "This notification was scheduled 30 seconds ago",
showTrigger: new TimestampTrigger(timestamp + 30 * 1000)
});
};

On desktop, the notification is triggered only if Chrome is running. On Android, they fire independently.

Cancel a scheduled notification

To cancel scheduled notifications, first request a list of all notifications that match a certain tag via ServiceWorkerRegistration.getNotifications (). Please note that you must pass the
includeTriggered Check for scheduled notifications to be listed:

const cancelScheduledNotification = async (tag) => {
const registration = await navigator.serviceWorker.getRegistration();
const notifications = await registration.getNotifications({
tag: tag,
includeTriggered: true,
});
notifications.forEach((notification) => notification.close());
};

Depuration

You can use the Chrome DevTools notification panel to debug notifications. To start debugging, press Start event recording record-8885793 or
Control+me (Command+me on Mac). Chrome DevTools logs all notification events, including scheduled, displayed, and closed notifications, for three days, even when DevTools is closed.

devtools-scheduled-4433090

A scheduled notification.

devtools-displayed-6666399

A notification displayed.

Manifestation

You can see the notification triggers in action in the manifestation, que le permite programar notificaciones, enumerar notificaciones programadas y cancelarlas. El source code está disponible en
Failure.

demo-9370521

Notification triggers manifestation.

Security and permissions

The Chrome team has designed and implemented the Notification Triggers API using the basic principles defined in Control access to powerful features of the web platform, including user control, transparency and ergonomics. Because this API requires service workers, it also requires a secure context. Using the API requires the same permission as regular push notifications.

User control

This API is only available in the context of a ServiceWorkerRegistration. This implies that all required data is stored in the same context and is automatically removed when the worker is removed from the service or when the user removes all data from the site for the source. Blocking cookies also prevents service workers from being installed on Chrome and thus this API from being used. The user can always disable notifications for the site in the site settings.

Transparency

Unlike the Push API, this API is not network dependent, which means that scheduled notifications need all the necessary data beforehand, including the image resources referenced by the badge,
icon and image atributos. Esto significa que mostrar una notificación programada no es observable por el desarrollador y no implica despertar al trabajador del servicio hasta que el usuario interactúe con la notificación. En consecuencia, actualmente no existe una forma conocida de que el desarrollador pueda obtener información sobre el usuario a través de enfoques potencialmente invasores de la privacidad como la búsqueda de geolocalización de direcciones IP. Este diseño también permite que la función aproveche opcionalmente los mecanismos de programming proporcionados por el sistema operativo, como el de Android.
AlarmManager, which helps conserve battery life.

Feedback

The Chrome team wants to hear about your experiences with notification triggers.

Tell us about the API design

Is there something in the API that is not working as you expected? Or are you missing any methods or properties you need to implement your idea? Have a question or comment about the security model? File a spec issue on the Notification Triggers GitHub repositoryor add your thoughts to an existing problem.

Problem with the implementation?

Found a bug with the Chrome implementation? Or is the implementation different from the specification? File a bug in new.crbug.com. Be sure to include as much detail as you can, simple instructions for reproducing and configuring Components UI> Notifications. Glitch works great for sharing bug replays quickly and easily.

Planning to use the API?

¿Planea usar activadores de notificación en su sitio? Su apoyo público nos ayuda a priorizar funciones y muestra a otros proveedores de browsers lo importante que es darles soporte. Enviar un tweet to
@Cromodev with #notificationtriggers and let us know where and how you are using it.

Helpful Links

Thanks

Notification Triggers was implemented by Richard Knoll
and the explainer written by Peter beverloo, con contribuciones de Richard. Las siguientes persons han revisado el artículo:
Joe medley, Pete LePageas well as Richard and Peter. Hero image for
Lukas blazek on Unsplash.