I'm trying to use the web-push plugin of node.js to implement push notifications on my web app.
// server.js
var webPush = require('web-push');
webPush.setGCMAPIKey("MY_API_KEY"); // I replace this with my key
router.post('/sendNotification', function(req, res) {
webPush.sendNotification({ endpoint: req.query.endpoint }, "Payload test here");
});
I got no error but i don't receive any notifications....
// index.js
var endpoint;
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
return registration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
return subscription;
}
return registration.pushManager.subscribe({ userVisibleOnly: true });
});
}).then(function(subscription) {
endpoint = subscription.endpoint;
}
document.getElementById('doIt').onclick = function() {
fetch(
'./sendNotification?endpoint=' + endpoint,
{ method: 'post' }
);
};
.
// service-worker.js
self.addEventListener('push', function(event) {
event.waitUntil(
self.registration.showNotification('header test', {
body: 'body test',
})
);
});
So when i click on my btn (#doIt), the server route /sendNotification is called well, with the right endpoint but... no notifications happend !
Hope you will be able to help me ! Thanks in advance !
You don't necessarily need the GCM API key, but you do need VAPID keys, see https://www.npmjs.com/package/web-push#usage . Make sure you have VAPID keys call webPush.setVapidDetails()
. If you're looking for a more detailed guide, I wrote a blog post on web push with Node.js .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.