Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: Creating a new tab after clicking on the notification

function notify(notifyMessage) {
    var options = {
        type: "basic",
        title: "My Extension",
        message: notifyMessage,
        iconUrl: "hello.png"
      };
    chrome.notifications.create("", options, function(notificationId) {
      setTimeout(function(){
        chrome.notifications.clear(notificationId, function(){});
      }, 2000);
    });
    chrome.notifications.onClicked.addListener(function(notificationId, byUser) {
        chrome.tabs.create({url: "http://www.google.com"});
    });
}

With this function, when I trigger notify for the first time and click on the notification, it creates one tab. When I trigger it for the second time and click, it creates two tab, etc. How should I reorganize my code to make it create only one tab each time?

like image 432
goldfrapp04 Avatar asked Mar 20 '23 06:03

goldfrapp04


1 Answers

The chrome.notifications.onClicked.addListener method adds an onclick listener to each of the notifications opened by your extension. Each call to this method adds another onclick listener to all of them: if you call that method 3 times, your notifications will each have 3 click listeners, and each one will open a tab.

To fix your code, you simply have to add the click handler outside of the notify function, to add only one onclick listener.

Note: the callback specified in the click listener will be passed the notification id of the notification that was actually clicked on, so that you can differentiate notifications if you open several at the same time.

The notification id is the first parameter of chrome.notifications.create. Here, you always pass "", so you'll always have at most one notification opened.

like image 191
Métoule Avatar answered Mar 21 '23 19:03

Métoule