javascript Chrome 桌面通知点击关注内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10390946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:42:37  来源:igfitidea点击:

Chrome desktop notification click to focus on content

javascriptgoogle-chromegoogle-chrome-extension

提问by Wade Tandy

I am building desktop notification into my a chrome extension that I am working on. The functionality I need required that the user be taken to the tab that caused the notification when they click on the notification window. I can get that working using the chrome.tabs API, but what I can't manage to figure out is how to bring Chrome to the front when the notification is clicked.

我正在将桌面通知构建到我正在开发的 chrome 扩展中。我需要的功能要求用户在单击通知窗口时被带到导致通知的选项卡。我可以使用 chrome.tabs API 使其工作,但我无法弄清楚如何在单击通知时将 Chrome 置于最前面。

I know window.focus() is disabled in chrome, but this is definitely possible to do since that's the behavior of the Gmail desktop notifications.

我知道 window.focus() 在 chrome 中被禁用,但这绝对是可能的,因为这是 Gmail 桌面通知的行为。

回答by dragon

notification = webkitNotifications.createNotification(...)
notification.onclick = function(){
    window.focus();
    this.cancel();
};
notification.show()

...works as expected, without any additional permissions.

...按预期工作,无需任何额外权限。

回答by Rob W

Use chrome.tabs.update(tabId, {active: true});to focus a tab (not to be confused with chrome.windows.update).

使用chrome.tabs.update(tabId, {active: true});集中标签(不要与混淆chrome.windows.update)。

The tabIdis often obtained via the Tabtype. This object is passed to many methods/event listeners (sometimes via the MessageSendertype).

tabId通常通过所获得的Tab类型。这个对象被传递给许多方法/事件侦听器(有时通过MessageSendertype)。

回答by Isayevskiy_Sergey

function msg(){
    var notification = new Notification("Title", {body: "Yore message", icon: "img.jpg" });
    notification.onshow = function() { setTimeout(notification.close(), 15000); };
    notification.onclick = function(){
        window.focus();
        this.cancel();
    };
}
msg();