2017-09-14 99 views
1

我使用serviceworker-webpack-plugin在我的respondjs应用程序中创建服务工作者。registration.show通知不是函数

我跟着the example在主线程中注册服务工作者。我了解到Html5 Notification在Android Chrome浏览器上无法正常工作,所以我使用registration.showNotification('Title', { body: 'Body.'});而不是new Notification('...')来推送通知。但是,当我测试了它在桌面上的镀铬,它抛出这个错误

registration.showNotification is not a function 

仅适用于Android铬可用,但不是在桌面上registration.showNotification?

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

回答

1

runtime.register()返回一个JavaScript的承诺,这就是为什么你得到一个not a function错误,因为承诺没有showNotification()方法。

相反,您必须将.then()回调链接到它以获取实际的registration对象(或使用异步/等待,这也很酷)。

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

谢谢。有用!希望服务人员有一个打字稿定义。 – RedGiant