Push API (Web Push) + Service Worker
Добрый день. Которую неделю бьюсь (безуспешно) над попыткой получить сообщение с сервера. Вроде и Service Worker регистрируется, вроде и сервер подтверждает успешную регистрацию... А сообщения не доходят. Очень нужна помощь.
P.S. Код клиента должен работать в Gecko 48 (старый Firefox), который например не знает функций async/await и т.д. Итак, есть код index.js function urlBase64ToUint8Array(base64String) { var padding = '='.repeat((4 - base64String.length % 4) % 4); var base64 = (base64String + padding) .replace(/\-/g, '+') .replace(/_/g, '/'); var rawData = window.atob(base64); var outputArray = new Uint8Array(rawData.length); for (var i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } var convertedVapidKey = urlBase64ToUint8Array( 'BNat99ai8SavGs2qUy6AS_UggxI6KwyYcarPRQNkSWMLegNc8a0hcBdRPlJ8y_JMVHuSqofk0xBtoyvbYHWM1g8' ) navigator.serviceWorker.register('service.js').then( function(serviceWorkerRegistration) { serviceWorkerRegistration.pushManager.subscribe( { applicationServerKey: convertedVapidKey, userVisibleOnly: true } ).then( function(pushSubscription) { console.log(pushSubscription); var info = {subscription: pushSubscription} var url = 'http://202.182.101.31:4000/save-subscription'; var xhr = new XMLHttpRequest({mozSystem: true}); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var json = JSON.parse(xhr.responseText); console.log(json); console.log('push service subscription successfull: ' + JSON.stringify(pushSubscription)); } }; var data = JSON.stringify(info); xhr.send(data); }, function(error) { console.log(error); } ); }); код service.js self.addEventListener('push', function(event) { console.log("event"); event.waitUntil( self.registration.showNotification('ServiceWorker Cookbook', { body: 'Alea iacta est', }) ); }); self.addEventListener('activate', function(active) { console.log("active"); }) При запуске в консоле вроде все ок. active service.js:11:3 PushSubscription { endpoint: "https://updates.push.services.mozilla.com/wpush/v2/gAAAAABfLjasOeeW-nnReeKSFRxNZ4PmSSgDsvUaBiQttqhi-KwSxauPaxJNKZdISfzlI8nD9WLdoM0yrbzFshAfZRhmEeUSmGkhCrbRB1RvyW2qlsYgGsxDa5CY-A4X_-DboBVVuKBriEMeUWT2eRISASSbCS2bCSLPxufNgLDetPm6gYOAvm0", options: PushSubscriptionOptions } index.js:37:9 Object { message: "success" } index.js:53:3 push service subscription successfull: {"endpoint":"https://updates.push.services.mozilla.com/wpush/v2/gAAAAABfLjasOeeW-nnReeKSFRxNZ4PmSSgDsvUaBiQttqhi-KwSxauPaxJNKZdISfzlI8nD9WLdoM0yrbzFshAfZRhmEeUSmGkhCrbRB1RvyW2qlsYgGsxDa5CY-A4X_-DboBVVuKBriEMeUWT2eRISASSbCS2bCSLPxufNgLDetPm6gYOAvm0","keys":{"auth":"gOP1jIP_lRhGdOCqtJRsGQ","p256dh":"BDYnBhhzBpLnhIQWD6QhHZSaX1BcAX4h-6SwYAuleHOTjY-yTq1HnBqHtiM_DqRfkG-NuX9kxi2g2uD4Xs-LZLc"}} Но, если я запускаю http://202.182.101.31:4000/send-notification сообщение не поступает, ходя написано { message: 'message sent' } P.S. Код сервера (который отправляет): const express = require('express') const cors = require('cors') const bodyParser = require('body-parser') const webpush = require('web-push') const app = express() app.use(cors()) app.use(bodyParser.json()) const port = 4000 app.get('/', (req, res) => res.send('Hello World!')) const dummyDb = { subscription: null } //dummy in memory store const saveToDatabase = async subscription => { // Since this is a demo app, I am going to save this in a dummy in memory store. Do not do this in your apps. // Here you should be writing your db logic to save it. dummyDb.subscription = subscription } // The new /save-subscription endpoint app.post('/save-subscription', async (req, res) => { const subscription = req.body await saveToDatabase(subscription) //Method to save the subscription to Database res.json({ message: 'success' }) }) const vapidKeys = { publicKey: 'BNat99ai8SavGs2qUy6AS_UggxI6KwyYcarPRQNkSWMLegNc8a0hcBdRPlJ8y_JMVHuSqofk0xBtoyvbYHWM1g8', privateKey: 'hlHd0rrSPSSCJgrKoG0NLoJGI_Wyfi_d4hjxr71Txps', } //setting our previously generated VAPID keys webpush.setVapidDetails( 'mailto:myuserid@email.com', vapidKeys.publicKey, vapidKeys.privateKey ) //function to send the notification to the subscribed device const sendNotification = (subscription, dataToSend) => { webpush.sendNotification(subscription, dataToSend) } //route to test send notification app.get('/send-notification', (req, res) => { const subscription = dummyDb.subscription //get subscription from your databse here. const message = 'Hello World' sendNotification(subscription, message) res.json({ message: 'message sent' }) }) app.listen(port, () => console.log(`Example app listening on port ${port}!`)) Помогите разобраться. Почему не получаю уведомления. |
Часовой пояс GMT +3, время: 09:11. |