最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chrome extension: Creating a new tab after clicking on the notification - Stack Overflow

programmeradmin4浏览0评论
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: ""});
    });
}

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?

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."});
    });
}

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?

Share Improve this question asked Jun 19, 2014 at 18:00 goldfrapp04goldfrapp04 2,3558 gold badges35 silver badges46 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论