gpt4 book ai didi

javascript - 服务 worker 的推送事件未被调用

转载 作者:行者123 更新时间:2023-11-29 10:07:04 25 4
gpt4 key购买 nike

我正在尝试接收来自 GCM 的推送消息。我只是简单地按照教程注册了 Service Worker,如下所示:-

      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);
});
});
}

Now, I get the device Id ("cw4jK8NhJgY:APA91bHr64E_kSdh7kN_VjcZRKulPf8KPLJLBjtnHI2qkYzx3-I9aUhunjzVcJjLtkHl9zvN8ys80gADK8tV8SueLX1R2jS0xgrf1Ur6cDw3jNjloUJp8PtWaIN-cEKXj69TZ9-D2Hiw")

来自网址:-“https://android.googleapis.com/gcm/send/cw4jK8NhJgY:APA91bHr64E_kSdh7kN_VjcZRKulPf8KPLJLBjtnHI2qkYzx3-I9aUhunjzVcJjLtkHl9zvN8ys80gADK8tV8SueLX1R2jS0xgrf1Ur6cDw3jNjloUJp8PtWaIN-cEKXj69TZ9-D2Hiw

在我的 service worker 文件中,我只是简单地听取如下推送消息:-

     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 天了。有人可以在这里帮助我吗?我在本地主机上执行此操作。

最佳答案

您没有返回 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

如果您需要任何详细信息,请告诉我

关于javascript - 服务 worker 的推送事件未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com