如何将焦点转移到创建桌面通知的 Chrome 选项卡?
我想实现与 Gmail 现在相同的功能。当新电子邮件到达或新聊天出现时,会出现通知弹出窗口,如果您单击它,Gmail 选项卡就会获得焦点。
我有这样的代码:
var n = window.webkitNotifications.createNotification('ico.gif', 'Title', 'Text');
n.onclick = function(x) { this.cancel(); };
n.show();
当我单击通知时,它就会消失。现在我需要向 onclick 函数添加一些代码,以显示并聚焦创建此通知的页面。我知道这是可能的,因为 GMail 做得很好。但我没有成功地调查 Gmail 来源(它们被最小化和混淆)。
有人知道该怎么做吗?
I would like to implement same functionality as Gmail has nowadays. When new email arrives or new chat comes, notification popup appears and if you click it, the tab with Gmail gets focussed.
I have this code:
var n = window.webkitNotifications.createNotification('ico.gif', 'Title', 'Text');
n.onclick = function(x) { this.cancel(); };
n.show();
When I click notification it makes it just disappear. Now I need to add some code to onclick function to bring up and focus page that created this notification. I know it is possible because GMail does it very well. But I didn't succeed in looking into Gmail sources (they are minimalized and obfuscated).
Anybody knows how to do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只需将 window.focus() 放置在 Google Chrome 中即可。单击时它将聚焦到该窗口。
我在 Gmail 中打开检查器,添加上述代码,移至另一个选项卡,然后运行它。通知出现了,点击后,我就回到了 Gmail。
You can just place window.focus() in Google Chrome. It will focus to that window when clicked.
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.
window.focus()
在最新的 Webkit 浏览器版本(Chrome、Safari 等)中并不总是有效。但parent.focus()
确实如此。这是一个完整的jsfiddle: https://jsfiddle.net/wv0w7uj7/3/
代码:
window.focus()
does not always work in recent Webkit browser versions (Chrome, Safari etc). Butparent.focus()
does.Here's a complete jsfiddle: https://jsfiddle.net/wv0w7uj7/3/
Code:
使用
onclick
属性并不是很好的做法,对于普通 javascript 使用addEventListener
或对于 jQuery 使用on
方法。普通:
jQuery:
It's not really good practice to use the
onclick
property, use theaddEventListener
for vanilla javascript oron
method for jQuery.Vanilla:
jQuery:
它应该是
this.close()
而不是this.cancel()
,如下所示:It should be
this.close()
rather thanthis.cancel()
, like this: