我有一个从服务器获取多个通知的 Service Worker。问题是 Chrome 中的所有通知都会自动关闭,除了最后一个。我究竟做错了什么?
self.addEventListener('push', function(event) {
var subscriptionId;
var sessionId;
var notification = {};
event.waitUntil(
self.registration.pushManager.getSubscription().then(function(subscription) {
subscriptionId = subscription.endpoint.split('/');
subscriptionId = subscriptionId[subscriptionId.length - 1];
notification.title = 'Yay a message.';
notification.icon = '/app/img/icon-256x256.png';
notification.tag = 'notification-tag-' + (new Date)*1;
notification.messages = [];
//get context
fetch(requestUrl,
{
method: 'post',
body: body
}).then(function(response) {
response.json().then(function(data) {
sessionId = response.headers.get('SessionId');
fetch(requestUrl + '?SessionId=' + sessionId, {
method: 'post',
headers: JSON.stringify({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
data: {
subscriberId: subscriptionId
}
})
}).then(function(responce) {
responce.json().then(function(data) {
data = data.data;
if (!data.chromeNotifications || !data.chromeNotifications.length) return;
data.chromeNotifications.forEach(function(push) {
notification.messages.push(push.message);
});
}).then(function() {
var promises = [];
for(var i=0; notification.messages && i<notification.messages.length; i++) {
promises.push(self.registration.showNotification(notification.title, {
body: notification.messages[i],
icon: notification.icon,
tag: notification.tag
}));
}
return Promise.all( promises );
});
});
})
});
}).catch(function(error) {
console.error('Unable to get subscription data', error);
var title = 'An error occurred';
var message = 'We were unable to get the information for this push message';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
tag: notificationTag
});
})
);