Сервисный работник вызывает проблемы с CORS в Firefox
Я использую сервисный работник для push-уведомлений, следуя этой статье. Все работает с Chrome, но с Firefox (v.44.0.2) у меня странная проблема. При успешном входе в мое приложение я регистрирую сервисного работника, который делает только ожидание push-событий; Я вижу, что правильно зарегистрирован (из некоторых журналов и из о: serviceworkers). Теперь, если я обновляю страницу (CTRL+R), все мои POST имеют проблемы с CORS (отсутствует заголовок Access-Control-Allow-Origin) из-за этого работника службы, и пользователь перенаправляется на страницу входа; отсюда все посты не работают по той же причине. И наоборот, если я вхожу в систему, отменяю регистрацию работника сервиса и затем обновляюсь, проблем вообще не возникает. Есть идеи о том, что происходит? Опять же, мой сервисный работник просто обрабатывает push-события, без кеширования и других обработок, и это прекрасно работает в Chrome
Вот мой код сервисного работника ( SOME_API_URL указывает на реальный API, который не нужен для целей тестирования, потому что проблема возникает после регистрации сервисного работника, никаких push-событий не требуется)
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('/');
}
})
);
});
1 ответ
В Firefox 44 есть ошибка 1243453, из-за которой заголовок Origin запросов из разных источников сбрасывается, если работник службы не прослушивает события выборки.
Ошибка была исправлена в Firefox 45, который выйдет на неделе 8 марта 2016 года (на следующей неделе, на момент написания этой статьи). В то же время, и для пользователей, которые не обновляются сразу до последней версии Firefox, вы можете обойти эту проблему, добавив этот код работнику службы:
addEventListener('fetch', function(evt) {
evt.respondWith(fetch(evt.request));
});