javascript - registration.showNotification 不是函数

标签 javascript android reactjs google-chrome service-worker

我正在使用 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/

相关文章:

java - 线程 hibernate ,不做

reactjs - Redux 待办事项列表高级

android - 如何仅使用 URL 自动单击网页上的按钮?

javascript - 仅在 Dropbox 中存储文件时,Datastore 和核心 API 之间的区别?

javascript - 使用 nodejs 为 postgresql 创建多个数据库表

javascript - 我的 PhoneGap 应用程序无法访问我的 Web 服务

android - fragment 动画问题

javascript - Gatsby Graphql 跳过

安卓:随机异常

reactjs - 重定向到 ReactJS 中的上一页