2011-02-05 15 views
62

Me gustaría implementar la misma funcionalidad que Gmail tiene hoy en día. Cuando llega un nuevo correo electrónico o aparece un nuevo chat, aparece la ventana emergente de notificación y si hace clic en él, la pestaña con Gmail se enfoca.¿Cómo enfocar una pestaña de Chrome que creó la notificación de escritorio?

tengo este código:

var n = window.webkitNotifications.createNotification('ico.gif', 'Title', 'Text'); 
n.onclick = function(x) { this.cancel(); }; 
n.show(); 

Al hacer clic en la notificación se hace simplemente desaparecer. Ahora necesito agregar algún código a la función onclick para abrir y enfocar la página que creó esta notificación. Sé que es posible porque GMail lo hace muy bien. Pero no logré ver las fuentes de Gmail (están minimalizadas y ofuscadas).

¿Alguien sabe cómo hacer esto?

Respuesta

82

Puedes simplemente colocar window.focus() en Google Chrome. Se enfocará en esa ventana cuando se haga clic.

var n = window.webkitNotifications.createNotification('ico.gif', 'Title', 'Text'); 
n.onclick = function(x) { window.focus(); this.cancel(); }; 
n.show(); 

me abrió el inspector en Gmail, añade el código anterior, se trasladó a una ficha diferente, y la pasó. Apareció la notificación y, una vez que se hizo clic, me devolvió a Gmail.

Espero que haya ayudado!

+3

Wow! ¡Así de simple! :-) Gran respuesta, gracias. Busqué en Google un buen rato, pero no pude encontrarlo. Ahora funciona perfectamente, gracias de nuevo. – Frodik

+1

¡Ningún problema! Diviértete pirateando :-) –

+0

Ahora no funciona http://jsfiddle.net/l2aelba/RhHgR/ :(, puedo hackear como alertar() para enfocar esta ventana – l2aelba

42

Usando Notifications.

if (typeof Notification !== 'undefined') { 
    alert('Please us a modern version of Chrome, Firefox, Opera or Safari.'); 
    return; 
} 

Notification.requestPermission(function (permission) { 
    if (permission !== 'granted') return; 

    var notification = new Notification('Here is the title', { 
    icon: 'http://path.to/my/icon.png', 
    body: 'Some body text', 
    }); 

    notification.onclick = function() { 
    window.focus(); 
    }; 
}); 
+0

'window.focus();' hace el truco! Debe estar marcado como la respuesta correcta. –

+0

'window.focus()' no funciona en Chrome 60, la solución de jazzcat con 'parent.focus()' funciona – pikax

0

Debe ser this.close() en lugar de this.cancel(), así:

var n = window.webkitNotifications.createNotification('ico.gif','Title', 'Text'); 
n.onclick = function(x) { window.focus(); this.cancel(); }; 
n.show(); 
14

window.focus() no siempre funciona en los últimos versiones del navegador Webkit (Chrome, Safari, etc). Pero parent.focus() hace.

Aquí hay una jsFiddle completa: https://jsfiddle.net/wv0w7uj7/3/

Código:

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: "You've been notified!", 
    }); 

    notification.onclick = function() { 
     parent.focus(); 
     window.focus(); //just in case, older browsers 
     this.close(); 
    }; 
    } 
} 
+0

¿por qué el downvote? – jazzcat

+0

Es normal tener 'esto' haciendo referencia a otro contexto, así que en lugar de llamar a 'this.close', es mejor llamar a 'evt.target.close' del evento 'onclick': ' notification.onclick = function (evt) { evt.target.close(); } ' –

2

En realidad no es una buena práctica usar la propiedad onclick, utilice el addEventListener de vainilla JavaScript o on método para jQuery.

var notify = new Notification('Test notification'); 

Vainilla:

notify.addEventListener('click', function(e) { 
    window.focus(); 
    e.target.close(); 
}, false); 

jQuery:

$(notify).on('click', function(e) { 
    window.focus(); 
    e.target.close(); 
}); 
Cuestiones relacionadas