gpt4 book ai didi

javascript - registration.showNotification 不是函数

转载 作者:太空狗 更新时间:2023-10-29 13:51:40 24 4
gpt4 key购买 nike

我正在使用 serviceworker-webpack-plugin在我的 reactjs 应用程序中创建服务 worker 。

我关注了the example在主线程中注册服务 worker 。我了解到 Html5 Notification 在 Android chrome 上不起作用,所以我使用了 registration.showNotification('Title', { body: 'Body.'});而不是 new Notification('...') 来推送通知。但是当我在桌面chrome上测试的时候,却抛出了这个错误

registration.showNotification is not a function

registration.showNotification 是否只能在 Android chrome 上使用,而不能在桌面上使用?

public componentDidMount(){

if ('serviceWorker' in navigator &&
(window.location.protocol === 'https:' || window.location.hostname === 'localhost')
) {
const registration = runtime.register();

registerEvents(registration, {
onInstalled: () => {

registration.showNotification('Title', { body: 'Body.'});
}
})
} else {
console.log('serviceWorker not available')
}
}

最佳答案

runtime.register() 返回一个 JavaScript Promise,这就是为什么您会收到 not a function 错误的原因,因为 Promises 没有 showNotification( ) 方法。

相反,您必须将 .then() 回调链接到它以获得实际的 registration 对象(或使用 async/await,这是也很酷)。

runtime.register().then(registration => {
registration.showNotification(...);
})

关于javascript - registration.showNotification 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46223677/

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