问题
This is My server.js code which uses web-push module to send the notification.
exports.sendWelcomePushNotification = function (req, res) {
var details = {
endpoint: req.body.endpoint,
key: req.body.key,
secret: req.body.authSecret
}
webPush.sendNotification(details.endpoint, {TTL: 0, payload: 'You have subscribed to Pushnotification.', userPublicKey: details.key, userAuth: details.secret}).then(function () {
res.sendStatus(200).json({message: 'User successfully subscribed'});
});
};
This my browser client side code to capture the endpoint, auth and key:
endpoint = subscription.endpoint;
var rawKey = subscription.getKey ? subscription.getKey('p256dh') : '';
key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : '';
var rawAuthSecret = subscription.getKey ? subscription.getKey('auth') : '';
authSecret = rawAuthSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) : '';
This is the service-worker code that listens for the notification:
self.addEventListener('push', function (event) {
var payload = event.data ? event.data.text() : 'No Text Body';
console.log(payload,'payload');
event.waitUntil(
self.registration.showNotification('Notify Message', {
lang: 'la',
body: 'You have subscribed to Pushnotification.',
icon: 'https://pushover.net/images/icon-256.png',
requireInteraction: true
})
);
});
This code is working fine for firefox.i.e; when i allow a notification, api request is sent and the web push is sending the push notification to the endpoint and iam able to get the welcome push notification. But the same code in chrome is not working. i.e; it is not giving any error and at the same time it is not giving the welcome push notification.
Can someone help me with this? Any kind of help is highly appreciated. Thanks.
回答1:
For Chrome, you'll need to either set a GCM API key (https://github.com/web-push-libs/web-push#setgcmapikeyapikey) or use VAPID (https://github.com/web-push-libs/web-push#using-vapid-key-for-applicationserverkey).
I'd suggest supporting them both, because Opera doesn't support VAPID but works with GCM.
回答2:
If you are using web-push it might have something todo with your encrypted data. Try the below code for server.js:
var webPush = require('web-push');
const VALID_SUBSCRIPTION = {
endpoint: 'your-endpoint-id',
keys: {
p256dh: 'userPublicKey',
auth: 'your-auth-secret'
}
};
var payload = {
title: "This is a title",
body: "this is the body",
icon: "images/someImageInPath.png"
}
webPush.setGCMAPIKey("your-gcmapikey");
webPush.sendNotification(VALID_SUBSCRIPTION.endpoint, {
TTL: 10,
payload: JSON.stringify(payload),
userPublicKey: VALID_SUBSCRIPTION.keys.p256dh,
userAuth: VALID_SUBSCRIPTION.keys.auth,
})
.then(function() {
console.log(JSON.stringify(payload));
});
来源:https://stackoverflow.com/questions/40042783/push-notification-is-not-being-sent-to-chromedesktop-level