Chrome扩展按钮侦听器在通知时执行多次



我正在编写一个chrome扩展,它向API发出请求,我注意到,在使用chrome的notification API从后台脚本创建通知后,通知按钮上的侦听器将被执行多次。在第一次跑步时只跑一次,然后增加。我想听众只是在页面上加起来,但我找不到刷新背景页面的方法。

这是创建通知及其侦听器的函数。

var myNotificationID
const displayNotification=(userEmail, password, website,username) =>{
chrome.notifications.create("", {
type:    "basic",
iconUrl: "./icon128.png",
title:   "PERMISSION",
requireInteraction: true,
message: "question",
buttons: [{
title: "YES",
}, {
title: "NO",
}]
}, function(id) {
myNotificationID = id;
})
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (notifId === myNotificationID) {
if (btnIdx === 0) {
console.log('inserting')
try{
fetch (`http://localhost:8080/users/${userEmail}/accounts`,{      
})
}catch(err){ 
}
} else if (btnIdx === 1) {
console.log('clearing')
chrome.notifications.clear(myNotificationID)
}
}
});
}

这就是这个函数被称为的地方

chrome.runtime.onMessage.addListener((message, sender, response)=>{
if(message.message === 'showNotification'){
console.log('received insert')
displayNotification(message.userEmail,message.password, message.currentSite,message.username)
response({status:"received"})
}
})

侦听器中的fetch被执行多次,但onMessage侦听器中日志只显示一次,因此侦听器是问题所在。我尝试了chrome.notifications.onButtonClicked.removeListener((,但正如我所提到的,没有成功。有没有其他方法可以在使用后从后台脚本中清除侦听器?

使用通知存储:

const notificationsByID = {};
chrome.notifications.onButtonClicked.addListener((notifId, btnIdx) => {
// Avoid access to the notification if not registered by displayNotification
if (!notificationsByID[ notifId ]) { return null; }
if (btnIdx === 0) {
console.log('inserting')
try{
fetch (`http://localhost:8080/users/${ notificationsByID[ notifId ].userEmail }/accounts`,{ /**/ });
}catch(err){
console.log(err);
}
delete notificationsByID[ notifId ]; // Cleanup
} else if (btnIdx === 1) {
console.log('clearing')
chrome.notifications.clear(myNotificationID);
delete notificationsByID[ notifId ]; // Cleanup
}
});
chrome.notifications.onClosed.addListener((notifId) => {
if (notificationsByID[ notifId ]) { delete notificationsByID[ notifId ]; }
});
const displayNotification=(userEmail, password, website,username) =>{
chrome.notifications.create("", {
type:    "basic",
iconUrl: "./icon128.png",
title:   "PERMISSION",
requireInteraction: true,
message: "question",
buttons: [{ title: "YES", }, { title: "NO", }]
}, function(id) {
// Insertion
notificationsByID[ id ] = { userEmail, password, website,username };
})
}

最新更新