我已经使用 Service Worker 实现了推送通知。有什么方法可以找出窗口中当前显示的通知数量?我的目的是限制窗口中显示的通知数量。
我尝试了以下方法。但 getNotifications 函数返回空数组。
self.addEventListener('push', function(event) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}
var data = event.data.json();
var options = {
body: data.notificationText,
icon: 'files/assets/staff.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
onClickUrl: data.onClickUrl,
event_id: data.event_id,
productName: data.product_name
}
};
event.waitUntil(
self.registration.getNotifications().then(function(notifications) {
console.log(notifications);
if (notifications && notifications.length > 0) {
notifications.forEach(function(notification) {
notification.close();
});
}
showNotification(data.title, options);
})
);
});
您可以使用serviceWorker.getNotifications()
它返回通知列表。你可以像这样使用它:
navigator.serviceWorker.register('sw.js');
navigator.serviceWorker.ready.then(function(registration) {
registration.getNotifications().then(function(notifications) {
// get the number of notifications
})
});
如果您在 serviceworker 文件中执行此操作,则为:
self.registration.getNotifications().then(function(notifications) {
// get the number of notifications
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)