Exemplo de notificação do ambiente de trabalho Chrome [fechado]
como é que se usa as notificações Chrome desktop ? Gostaria que usasse isso no meu próprio código.
Update : aqui está um post explicando as notificações do webkit com um exemplo.
9 answers
Abaixo está um exemplo de trabalho de notificações de desktop para Chrome, Firefox, Opera e Safari. Note que, por razões de segurança, a começar pelo Chrome 62, a permissão para a API de notificação pode já não ser solicitada a partir de uma iframe de origem cruzada, por isso terá de gravar este exemplo num ficheiro HTML no seu site/aplicação, e certifique-se de usar o 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 a usar as notificações W3C API, documentadas em MDN. Não confunda isto. com a APIdas extensões Chrome, que é diferente. As notificações de extensão do Chrome obviamente só funcionam em extensões do Chrome, não necessitam de nenhuma permissão especial do utilizador, suportam notificações de texto ricas, mas desaparecem automaticamente e o utilizador pode não reparar que foram despoletadas ). As notificações W3C funcionam em muitos navegadores (ver Suporte em caniuse ), requerem permissão do utilizador, empilham no topo da notificação anterior e não automaticamente desaparecer no cromado (fazem-no no Firefox).
Palavras finais
O apoio à notificação tem estado em fluxo contínuo, tendo várias API sido desactualizadas nos últimos três anos. Se você está curioso, verifique as edições anteriores desta resposta para ver o que costumava funcionar no Chrome, e para aprender a história de ricas notificações HTML.
Agora a última norma é em https://notifications.spec.whatwg.org/.
Há também uma chamada diferente. com os mesmos parâmetros) para criar notificações de trabalhadores de serviços, que por alguma razão, não têm acesso ao construtorNotification()
.
Ver também notificar.js para uma biblioteca auxiliar.
Verifique adesign e API Especificação (ainda é um rascunho) ou verifique a fonte a partir de (a página já não está disponível) para um exemplo simples: é principalmente uma chamada para window.webkitNotifications.createNotification
.
Se quiser um exemplo mais robusto (está a tentar criar a sua própria extensão do Google Chrome, e gostaria de saber como lidar com permissões, armazenamento local e assim), verifique extensão do Gmail notificante: baixe o ficheiro crx em vez de o instalar, desaperte-o e leia a sua codigo.
Parece que window.webkitNotifications
já foi desacreditado e removido. No entanto, há uma nova API , e parece funcionar na última versão do Firefox também.
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.
}
Eu gosto: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples mas usa variáveis antigas, por isso a demonstração já não funciona. webkitNotifications
é agora Notification
.
Notificar.js é uma embalagem em torno das novas notificações webkit. Funciona muito bem.
Http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/
$ bower install js-notify
É assim que funciona:
notify('title', {
body: 'Notification Text',
icon: 'path/to/image.png',
onclick: function(e) {}, // e -> Notification object
onclose: function(e) {},
ondenied: function(e) {}
});
Você tem que definir o título, mas o objeto json como o segundo argumento é opcional.
<!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>
Por alguma razão a resposta aceite não funcionou para mim, acabei por usar o seguinte exemplo:
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) {});
}