如何让焦点集中在创建桌面通知的 Chrome 标签上?

我想实现和 Gmail 现在一样的功能。当收到新邮件或者新聊天信息时,会弹出一个通知窗口,如果你点击它,Gmail 的标签页就会显示出来。

我有这个密码:

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

当我点击通知,它就会消失。现在我需要添加一些代码到 onclick 函数中,以打开创建此通知的焦点页面。我知道这是可能的,因为 GMail 做得很好。但是我没有成功地查看 Gmail 的源代码(它们被最小化和模糊化了)。

有人知道怎么做吗?

35352 次浏览

You can just place window.focus() in Google Chrome. It will focus to that window when clicked.

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

I opened the inspector in Gmail, added the above code, moved to a different tab, and ran it. The notification appeared and once clicked, it brought me back to Gmail.

Using 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();
};
});

It should be this.close() rather than this.cancel(), like this:

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

window.focus() does not always work in recent Webkit browser versions (Chrome, Safari etc). But parent.focus() does.

Here's a complete jsfiddle: https://jsfiddle.net/wv0w7uj7/3/

Code:

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();
};
}
}

It's not really good practice to use the onclick property, use the addEventListener for vanilla javascript or on method for jQuery.

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

Vanilla:

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

jQuery:

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