Api de notificaciones

13 de mayo de 2013 by stripTM with No hay comentarios »

El api de notificaciones pone a disposición de los desarrolladores un sistema de notificaciones fuera del contexto de la la página, la manera en como se muestran cae fuera de la especificación y es el navegador / sistema operativo el que se encargará de esto, en dispositivos móviles por ejemplo suele aparecer un indicador del número de notificaciones pendientes en la parte superior de la pantalla y el usuario tiene que ‘bajar la persiana’ para leerlas mientras que en escritorio al disponer de espacio suficiente es habitual que aparezcan en una de las esquinas de la pantalla sin necesidad de acción por parte del usuario.

A fecha de hoy (mayo de 2013) el Web Notifications API aun se encuentra en fase de borrador del W3C, donde recientemente ha sufrido modificaciones en su uso, en el caso de Mozilla estos cambios han sido implementados en la versión 22 de Firefox Aurora con lo que si vas a probarlo asegúrate que el navegador implementa esta revisión, incluso al ser tan reciente posiblemente no esté implementado el 100% del api.

Una de las ventajas que incluye este api frente a por ejemplo los clásicos alert es que implementa un sistema de permisos que dará poder al usuario para conceder que una determinada página web pueda lanzar o no este tipo de notificaciones.

Otro avance es permitir listas de notificaciones de tal forma que el sistema operativo puede organizarlas de tal forma que al usuario se le muestren de una forma más ordenada en el caso que tenga diferentes sitios abiertos lanzando mensajes.

Permisos

Ventana de permisosEl usuario dispone de 3 estados, default, denied y granted, default y denied indican que no quiere que se muestren notificaciones, denied es cuando explícitamente lo ha elegido y no mostrará una posible petición de permisos si se solicitasen.

Por el contrario granted indica que si que quiere que se muestren, desde javascript puede consultarse en el atributo permission:
Notification.permission

Desde el navegador haciendo clic en el ‘favicon‘ de la barra de direcciones del sitio, pulsando en más información y en la pestaña permisos aparece la lista de elementos a los que el usuario da o concede permisos y desde allí mismo se puede modificar.

Uso

El api de notificación dispone de 3 métodos y un atributo de sólo lectura,

  • Constructor(título, opciones) . El título es el mensaje que se quiere enviar. Las opciones un array clave/valor donde se encuentran el cuerpo de mensaje, dirección del título de la notificación, dirección del cuerpo de la notificación, tag para indicarle si pertenece a algún conjunto o lista y una url para un icono que acompañe a la notificación.
  • requestPermission(callback) si el usuario no ha rechazado previamente las notificaciones mostrara un diálogo solicitandoselo, el resultado de desta acción se podrá consultar en el callback.
  • close() permite eliminar las notificaciones pendientes que hubiese.
  • permission indica como tiene el usuario configuradas las notificaciones para el sitio (default, denied o granted).

El siguiente ejemplo podría la típica forma de uso.
Comprobamos si el navegador implementa notificaciones.
Solicitamos permisos para poder mostrarlos y

1
2
3
4
5
6
7
if (Notification) {
	if (Notification.permission !== "granted") {
		Notification.requestPermission();
	}
	var notificacion = new Notification("Notificación que sólo se muestra durante un segundo");
	setTimeout(function() {notificacion.close()}, 1000);
}

Ejemplo de notificación con detalle y perteneciente a la lista ‘calendario’.

new Notification(
  "Aviso calendario",
  {
    body : "21:00h Reunión mumble MH Labs.",
    tag: 'calendario'
  });

Compatibilidad hacia atrás

Si no has seguido los consejos e hiciste uso en producción del api cuando aun tenía prefijos aún hay remedio. Básicamente lo que se debe hacer en el código es ir interrogando si implementa el estándar, si lo implementa con el prefijo -moz, si lo implementa con el -webkit… y dentro de cada bloque su código correspondiente.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
if (window.Notification) {
    notification = new Notification('Alarm - TimerX3', {
        icon: 'logo-64.png',
        body: 'A timer finished',
    });
    notification.onclose = function() {
        that.dismissAlarm();
    };
} else if (navigator.mozNotification) {
    var icon30 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAMAAAAM7l6QAAABI1BMVEX/////AAD/SQD/VQD/UAD/TwD/TQD/TgD/TgDdXSTdXCbiWyD/TgD/TgD/TgD4Ugn3Ugn/TgD/aSb/UgX/VQn+UQUAAAAGBgYKCgoMDAwhISEpKSkqKio9PT1NTU1YWFhkZGR1dXV4eHh7e3uFhYWIiIiRkZGTk5OVlZWjo6OqqqqrjoGsj4KsrKytkIOukYSxsbG5ubm8vLzAwMDDw8PExMTHx8fIyMjJycnKysrMzMzPz8/Q0NDS0tLT0NDT09PU1NTV0tLV1dXW1tbX19fY2Njb29vc3Nzd3d3f39/j4+Pl5eXnZCvoXB/o6Ojq6urr6+vz8/P19fX29vb39/f6+vr7+/v9/f3+/v7/TgD/mWz/rIf/rIj/0b3/3M3//Pv///8N30akAAAAFnRSTlMAAQcMEB1CW2h+f5ewu9Lv8Pr8/f3+XL7/kwAAAZVJREFUKM+Fk2lbgkAUhTH3FE1c2nfSsLLUwlK0stJSySUrLm73//+KhkVg2rwfeM7wMsPcM2cYxi6Pzx8K+X0e5pdaCrAx0CvGBpa+QdfyCgEJrtPhEkREgy4ndYcBkupkhoKAs4maBAi7beqNAMgnCqKGEZWcDBDxWnMjEB/X+DIhrRZ5SHxtFIeIOd8VhvgUMftASF28qfces4jTOISN/wcBxmhWXSRV6RM1AgjqHUVBrlFYLPUQazJEtf4CkMzxWQqLpW6WzyUhQDALqiI9UTi/u1mXFBVY4mQMJojOxS8P1lf33xAnEPMwPkjMKHy8kdppaHqWAB/jB86mw8O97dRW3hxx4GdC0BGEtvkik0qtpT902RaEDoR+4CNTmphePJMZ2iNtcXprztK35mysic8DcW6B0ZjTlnL1WlEKuryrGLY4TX1PD7Bxocsz/tQw1XEkxdeCgsW+ru/NI7EP9LOJL92rW+PT+YFacbD2RMdhHiZJM0MzqEqFyYxizooinlNRXBRk8v9g9J9rsOgS/XUFvwD41b0VEaL41wAAAABJRU5ErkJggg==';
    notification = navigator.mozNotification.createNotification(
       'Alarm - TimerX3',
       'A timer finished',
        icon30);
    notification.onclick = function () {
        navigator.mozApps.getSelf().onsuccess = function(evt) {
            var app = evt.target.result;
            app.launch();
        };
    };
    notification.show();
}
} else if (/* Aquí el resto de implementaciones de otros navegadores*/) {
  /* Aquí como lo manejan */
}

Referencias

  1. http://www.w3.org/TR/notifications/

  2. “>http://www.mozilla.org/en-US/firefox/22.0a2/auroranotes/
  3. https://bugzilla.mozilla.org/show_bug.cgi?id=782211

Mozilla y OTOY presentan nuevo codec de video en JavaScript

13 de mayo de 2013 by deimidis with No hay comentarios »

noticia escrita por Carlos Solís

Mozilla y OTOY (creadores del motor Octane Render) están actualmente trabajando en el proyecto ORBX.js, un sistema que permite transmitir video por streaming y decodificarlo directamente en el navegador, usando solamente tecnología JavaScript asistida por la GPU. Usualmente esto no sería muy distinto de otros sistemas creados para ello (como por ejemplo WebRTC), pero este en particular ofrece la ventaja de poder usar cualquier códec que pueda implementarse en la plataforma sin necesidad de hacer cambios al navegador. Esto lo vuelve apto para poder ser utilizado para aplicaciones de cualquier tipo, con una alta capacidad de mejora a futuro.

Actualmente, ORBX.js está siendo empleado especialmente como un sistema para transmitir y ejecutar a distancia todo tipo de programas en navegadores de escritorio o móvil, indistintamente del sistema operativo de origen, y sin necesidad de que el sistema de destino sea muy potente: basta solamente con que tenga la capacidad para decodificar el stream recibido y una conexión a Internet de suficiente velocidad. Inclusive, gracias a las tecnologías abiertas, estas aplicaciones pueden ejecutarse como si fueran nativas del sistema operativo de destino, o permitir que la ejecución del programa se reparta entre el sistema de destino y el de origen, como si se tuviera una GPU adicional en la nube.

Otra de las ventajas del sistema es que no requiere DRM (Digital Right Management o Gestión de derechos digitales) para funcionar; el gestor de contenido, si desea, puede usar un sistema de marcas de agua para identificar el stream que se está transmitiendo, lo que es suficiente en muchos casos para evitar el uso no autorizado, sin necesidad de usar tecnologías restrictivas del lado del usuario. Esto se vuelve más imprescindible tras las últimas discusiones sobre agregar sistemas de DRM al estándar web a pedido de las productoras de Hollywood.

ORBX.js promete un panorama interesante a futuro para las aplicaciones web, permitiendo que tengan alta potencia gráfica sin necesidad de depender del sistema de destino para ello. Mozilla, con este proyecto, buscará lograr que las tecnologías web estén a la par de las tecnologías nativas, lo que podría significar una revolución para la Internet del futuro.

Personalization with Respect

10 de mayo de 2013 by jsullivan with No hay comentarios »

Mozilla’s mission compels us to provide people with an Internet experience that puts them in control of their online lives and that treats them with respect. Respecting someone includes respecting their privacy. We aspire to a “no surprises” principle: the idea that when information is gathered about a person, it is done with their knowledge and is used in ways that benefit that person. People should be made aware of how information is collected and used. Each individual should also be able to decide whether the exchange of personal data for the services received in return feels fair. This can be challenging to achieve, especially when balanced against convenience and ease of use: people expect a fast, streamlined user experience without excessive prompts and confusing choices. But we are always striving toward this ideal.

Mozilla is an active participant in the ecosystem of today’s Web economics. Much of the content and information that people enjoy and benefit from is funded by digital marketing and sponsorship. This is a valid business model. We simply believe that when personal data is collected to deliver these services, the collection should be done respectfully and with the consent of the consumer. Commerce works best when users understand the transactions they engage in. The best long-term customer relationships are built on trust.

Mozilla aspires to enable personalization — the customization of ads, content, recommendations, offers and more — that doesn’t rely on the user being in the dark about who has access to that information, and with whom that information is shared. As a major Web browser provider and, now, OS developer, Mozilla’s role is to experiment and innovate toward that aspiration. As an open source project, where contributions are welcomed by all, we encourage all in the industry to help, by constructively proposing approaches and collaborating with us in the open.

Here are a just a few examples of the work Mozilla is doing to explore personalization with respect:

  • Persona is an identity system for the Web. It gives people control over their Web logins. People choose what identity to present to a given service. In particular, people can keep their work, personal, and other facets of their lives distinct.
  • Do Not Track allows you to tell a website that you would like to opt-out of third-party tracking for purposes including behavioral advertising. It lets users express how they would like information about themselves to be handled. It has many benefits. People who use Firefox must actively enable Do Not Track, making it very clear that the user has made an explicit choice Also, Do Not Track is independent of any particular technology, providing resilience in the face of technology evolution. We continue to work with a broad range of interested parties to see the Web adopt Do Not Track.
  • Third party cookie policies are being evaluated to strike a better balance between personalized ads and the tracking of users across the Web without their consent. For example, an experimental version of Firefox allows cookies to be set by first parties and by third parties where Firefox has stored a cookie for the party’s domain, but to block by default third-party cookies whose domain is not known from Firefox’s cookie store. We’ve been evaluating that approach, as well as others, working with stakeholders from across the industry.

It should be possible to delight users (and yes, the right offer at the right time can be a delight), while treating them with respect. We continue to experiment with and evaluate new ways to put users in control of their Web experience and encourage you to join us in building toward this vision. We will share more updates soon.