我正在尝试接收来自GCM的推送消息。我只是按照教程并注册了服务工作者,如下所示: -
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
var subscribeForPush = function() {
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey : urlB64ToUint8Array('<API-KEY>')
})
.then(function(subscription) {
console.log("Subscription for Push successful: ", subscription);
})
.catch(function(error) {
console.log("Subscription for Push failed", error);
});
});
};
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
subscribeForPush();
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
现在,我得到的装置ID( “ cw4jK8NhJgY:APA91bHr64E_kSdh7kN_VjcZRKulPf8KPLJLBjtnHI2qkYzx3-I9aUhunjzVcJjLtkHl9zvN8ys80gADK8tV8SueLX1R2jS0xgrf1Ur6cDw3jNjloUJp8PtWaIN-cEKXj69TZ9-D2Hiw ”)
来自网址的在我的服务工作者文件中,我只是听取推送消息,如: -
self.addEventListener('push', function(event) {
console.log(event)
});
我可以使用终端向gcm发送消息并获取消息: -
{"multicast_id":4983340130324592129,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1483043226210433%cc9b4facf9fd7ecd"}]}
但我不知道为什么我看不到推送监听器中的日志?我被困在这个问题上超过2天。有人可以帮我吗?我在localhost中这样做。
答案 0 :(得分:2)
您没有返回pushManager订阅
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
return serviceWorkerRegistration.pushManager.subscribe({
'userVisibleOnly': true
}).then(function(subscription) {
if (!subscription) {
// Set appropriate app states.
return;
}
console.log(subscription.endpoint);
}).catch(function (err) {
console.log('error in subcription .. '+ err);
});
})
检查我的github项目https://github.com/bvakiti/bvakiti.github.io/blob/master/app.js
如果您需要任何细节,请告诉我
答案 1 :(得分:1)
我想通过宣布
来增加bvakiti的解决方案applicationServerKey: convertedVapidKey
在pushManager订阅中。我在互联网上找到的大多数教程都使用了bvakiti的方法,大多数遵循该教程的开发人员在接收推送通知时遇到了问题。