gpt4 book ai didi

javascript - 在点击提示之前推送通知 "Error Registration failed - permission denied"?

转载 作者:行者123 更新时间:2023-12-02 23:57:18 25 4
gpt4 key购买 nike

我正在尝试学习如何使用推送通知,但我收到了

Registration failed - permission denied

甚至在我单击允许或阻止权限提示之前就出现错误。

在我的服务工作人员文件中产生此错误的行是

const subscription = await self.registration.pushManager.subscribe(options)

奇怪的是,如果我在错误后单击“允许通知”并刷新页面,一切正常。

当我检查window.Notification.requestPermission时,它返回granted

大部分代码来自https://blog.atulr.com/web-notifications/

const urlB64ToUint8Array = base64String => {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
const rawData = atob(base64)
const outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}

const saveSubscription = async subscription => {
const SERVER_URL = 'http://localhost:8081/save-subscription'
const response = await fetch(SERVER_URL, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(subscription),
})
return response.json()
}

self.addEventListener('activate', async () => {
// This will be called only once when the service worker is installed for first time.
try {
const applicationServerKey = urlB64ToUint8Array(
'BO29MqroVuQiUch951aG0kASkvQy9S4OLshzA3xc12Ar3oAT7UMxjlsq3OMlQXQaSsZILLy7nWuvmbZNZ1YOrXo'
)
const options = { applicationServerKey, userVisibleOnly: true }
const subscription = await self.registration.pushManager.subscribe(options)
const response = await saveSubscription(subscription)
console.log(response)
} catch (err) {
console.log('Error', err.message)
}
})

self.addEventListener('push', function(event) {
if (event.data) {
console.log('Push event!! ', event.data.text())
showLocalNotification('Yolo', event.data.text(), self.registration)
} else {
console.log('Push event but no data')
}
})

const showLocalNotification = (title, body, swRegistration) => {
const options = {
body,
// here you can add more properties like icon, image, vibrate, etc.
}
swRegistration.showNotification(title, options)
}

最佳答案

在注册 Service Worker 或订阅推送服务之前,您需要请求通知权限。

根据https://blog.atulr.com/web-notifications/中的代码,将index.js中以下两条语句的顺序更改为

const swRegistration = await registerServiceWorker();
const permission = await requestNotificationPermission();

const permission =  await requestNotificationPermission();    
const swRegistration = await registerServiceWorker();

这应该可以修复下面的错误消息。

Registration failed - permission denied

关于javascript - 在点击提示之前推送通知 "Error Registration failed - permission denied"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55316397/

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