按照这篇文章,我正在使用服务工作者进行推送通知。一切都适用于 Chrome,但使用 Firefox (v.44.0.2) 我有一个奇怪的问题。成功登录我的应用程序后,我注册了只等待推送事件的服务工作者;我看到它已正确注册(来自一些日志记录和about:serviceworkers)。现在,如果我刷新页面 (CTRL+R),我的所有 POST 都会由于这个服务工作者而出现 CORS 问题(缺少Access-Control-Allow-Origin标头),并且用户被重定向到登录页面;出于同样的原因,从这里开始,所有 POST 都不起作用。相反,如果我登录,请取消注册服务人员并然后刷新,完全没有问题。知道发生了什么吗?同样,我的服务人员只处理推送事件,没有缓存没有其他处理完成,它在 Chrome 上完美运行。
这是我的服务工作者代码( SOME_API_URL 指向一个真实的 API,它不需要用于测试目的,因为问题发生在服务工作者注册后,不需要推送事件)
self.addEventListener('push', function(event) {
// Since there is no payload data with the first version
// of push messages, we'll grab some data from
// an API and use it to populate a notification
event.waitUntil(
fetch(SOME_API_URL).then(function(response) {
if (response.status !== 200) {
// Either show a message to the user explaining the error
// or enter a generic message and handle the
// onnotificationclick event to direct the user to a web page
console.log('Looks like there was a problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification.title;
var message = data.notification.message;
var icon = data.notification.icon;
var notificationTag = data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
}).catch(function(err) {
console.error('Unable to retrieve data', err);
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
});
})
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow('/');
}
})
);
});