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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With