Created
September 24, 2017 18:46
-
-
Save nicdnepr/91f6d4be7c4c2d75e62ec96fa680ac91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
importScripts('https://www.gstatic.com/firebasejs/4.3.0/firebase-app.js'); | |
importScripts('https://www.gstatic.com/firebasejs/4.3.0/firebase-messaging.js'); | |
firebase.initializeApp({ | |
messagingSenderId: '' | |
}); | |
const messaging = firebase.messaging(); | |
self.addEventListener('notificationclick', function(event) { | |
const target = event.notification.data.click_action || '/'; | |
event.notification.close(); | |
// This looks to see if the current is already open and focuses if it is | |
event.waitUntil(clients.matchAll({ | |
type: 'window', | |
includeUncontrolled: true | |
}).then(function(clientList) { | |
// clientList always is empty?! | |
for (var i = 0; i < clientList.length; i++) { | |
var client = clientList[i]; | |
if (client.url == target && 'focus' in client) { | |
return client.focus(); | |
} | |
} | |
return clients.openWindow(target); | |
})); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
firebase.initializeApp({ | |
messagingSenderId: '' | |
}); | |
// браузер поддерживает уведомления | |
// вообще, эту проверку должна делать библиотека Firebase, но она этого не делает | |
if ('Notification' in window) { | |
var messaging = firebase.messaging(); | |
messaging.onMessage(function(payload) { | |
new Notification(payload.notification.title, payload.notification); | |
}); | |
subscribe(); | |
} | |
function subscribe() { | |
// запрашиваем разрешение на получение уведомлений | |
messaging.requestPermission() | |
.then(function () { | |
// получаем ID устройства | |
messaging.getToken() | |
.then(function (currentToken) { | |
if (currentToken) { | |
sendTokenToServer(currentToken); | |
} else { | |
console.warn('Не удалось получить токен.'); | |
setTokenSentToServer(false); | |
} | |
}) | |
.catch(function (err) { | |
console.warn('При получении токена произошла ошибка.', err); | |
setTokenSentToServer(false); | |
}); | |
}) | |
.catch(function (err) { | |
console.warn('Не удалось получить разрешение на показ уведомлений.', err); | |
}); | |
} | |
// отправка ID на сервер | |
function sendTokenToServer(currentToken) { | |
if (!isTokenSentToServer(currentToken)) { | |
var url = '/token'; // адрес скрипта на сервере который сохраняет ID устройства | |
$.post(url, { | |
token: currentToken | |
}); | |
setTokenSentToServer(currentToken); | |
} | |
} | |
// используем localStorage для отметки того, | |
// что пользователь уже подписался на уведомления | |
function isTokenSentToServer(currentToken) { | |
return window.localStorage.getItem('sentFirebaseMessagingToken') == currentToken; | |
} | |
function setTokenSentToServer(currentToken) { | |
window.localStorage.setItem( | |
'sentFirebaseMessagingToken', | |
currentToken ? currentToken : '' | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment