Ejemplo de notificación de Chrome desktop [cerrado]
¿Cómo se utiliza Chrome desktop notificaciones? Me gustaría que lo usara en mi propio código.
Actualización : Aquí está una entrada de blog explicando las notificaciones de webkit con un ejemplo.
9 answers
A continuación se muestra un ejemplo de trabajo de notificaciones de escritorio para Chrome, Firefox, Opera y Safari. Tenga en cuenta que, por razones de seguridad, a partir de Chrome 62, el permiso para la API de notificaciones ya no se puede solicitar desde un iframe de origen cruzado, por lo que deberá guardar este ejemplo en un archivo HTML en su sitio/aplicación y asegúrese de usar HTTPS.
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: "Hey there! You've been notified!",
});
notification.onclick = function () {
window.open("http://stackoverflow.com/a/13328397/1269037");
};
}
}
<button onclick="notifyMe()">Notify me!</button>
Estamos utilizando la API W3C Notifications, documentada en MDN. No confunda esto con la API de notificaciones de extensiones de Chrome , que es diferente. Las notificaciones de extensiones de Chrome obviamente solo funcionan en extensiones de Chrome, no requieren ningún permiso especial del usuario, admiten notificaciones de texto enriquecido, pero desaparecen automáticamente y el usuario puede no notar que se han activado). Las notificaciones W3C funcionan en muchos navegadores (ver soporte en caniuse ), requieren permiso del usuario, se apilan encima de la notificación anterior y no se hacen automáticamente desaparecen en Chrome (lo hacen en Firefox).
Palabras finales
El soporte de notificaciones ha estado en continuo flujo, con varias API obsoletas en los últimos tres años. Si tienes curiosidad, revisa las ediciones anteriores de esta respuesta para ver lo que solía funcionar en Chrome, y para aprender la historia de las notificaciones HTML enriquecidas.
Ahora el último estándar es https://notifications.spec.whatwg.org/.
También hay una llamada diferente (aunque con los mismos parámetros) para crear notificaciones de trabajadores de servicio, que por alguna razón, no tienen acceso al constructor Notification()
.
Véase también notificar.js para una biblioteca de ayuda.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-14 22:23:43
Compruebe el diseño y la especificación API (todavía es un borrador) o compruebe la fuente desde (la página ya no está disponible) para ver un ejemplo simple: Es principalmente una llamada a window.webkitNotifications.createNotification
.
Si quieres un ejemplo más robusto (estás tratando de crear tu propia extensión de Google Chrome, y te gustaría saber cómo lidiar con los permisos, el almacenamiento local y demás), echa un vistazo Gmail Notifier Extension: descarga el archivo crx en lugar de instalarlo, descomprímelo y lee su fuente codificar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-04 13:04:53
Parece que window.webkitNotifications
ya ha sido obsoleto y eliminado. Sin embargo, hay un nueva API, y parece funcionar en la última versión de Firefox, así.
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check if the user is okay to get some notification
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
// Note, Chrome does not implement the permission static property
// So we have to check for NOT 'denied' instead of 'default'
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if(!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user already denied any notification, and you
// want to be respectful there is no need to bother him any more.
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-31 20:41:38
Me gusta: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples pero utiliza variables antiguas, por lo que la demo ya no funciona. webkitNotifications
es ahora Notification
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 17:38:51
Notificar.js es un envoltorio alrededor de las nuevas notificaciones de webkit. Funciona bastante bien.
Http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-03 22:04:12
Hice este envoltorio de notificación simple. Funciona en Chrome, Safari y Firefox.
Probablemente en Opera, IE y Edge también, pero aún no lo he probado.
Solo recibe la notificación.archivo js desde aquí https://github.com/gravmatt/js-notify y ponlo en tu página.
Consíguelo en Bower
$ bower install js-notify
Así es como funciona:
notify('title', {
body: 'Notification Text',
icon: 'path/to/image.png',
onclick: function(e) {}, // e -> Notification object
onclose: function(e) {},
ondenied: function(e) {}
});
Debe establecer el título, pero el objeto json como segundo argumento es opcional.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-27 13:18:36
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script>
function notify(){
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
else{
var notification = new Notification('hello', {
body: "Hey there!",
});
notification.onclick = function () {
window.open("http://google.com");
};
}
}
</script>
</head>
<body>
<button onclick="notify()">Notify</button>
</body>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-07 09:41:49
Aquí hay una buena documentación sobre las API,
Https://developer.chrome.com/apps/notifications
Y, explicación de video oficial de Google,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-11 06:32:48
Por alguna razón la respuesta aceptada no funcionó para mí, terminé usando el siguiente ejemplo:
Https://developer.chrome.com/apps/app_codelab_alarms#create-notification
function notifyMe() {
chrome.notifications.create('reminder', {
type: 'basic',
iconUrl: 'icon.png',
title: 'Don\'t forget!',
message: 'You have things to do. Wake up, dude!'
}, function(notificationId) {});
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-09 07:22:56