15

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.

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.

Wade Tandy
  • 4,026
  • 3
  • 23
  • 31

3 Answers3

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

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

dragon
  • 1,747
  • 15
  • 18
  • 1
    This is wrong, this is for the HTML5 api, he is asking about the chrome extension API. – RVera May 30 '14 at 23:21
  • This does not work for me either. Clicking on the notification just closes the notification and does not set the focus on the window. – Marko Aug 11 '15 at 15:49
  • I posted an updated answer here: http://stackoverflow.com/a/40964355/714733 – jazzcat Dec 04 '16 at 22:19
6

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

The tabId is often obtained via the Tab type. This object is passed to many methods/event listeners (sometimes via the MessageSender type).

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • I want to make sure both the tab is set active and the window gets focused. Do you happen to know if it is harmful to do both in parallel or should I set the tab active first, and then set the window focused in the callback? – Cody Allan Taylor Sep 07 '17 at 21:20
4
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();

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131