2017-09-14 2 views
1

Ich verwende serviceworker-webpack-plugin, um einen Service-Mitarbeiter in meinen reactjs-Apps zu erstellen.registration.showNotification ist keine Funktion

Ich habe the example gefolgt, um den Service Worker im Hauptthread zu registrieren. Ich habe gelernt, dass Html5 Notification funktioniert nicht auf Android-Chrom, so dass ich registration.showNotification('Title', { body: 'Body.'}); anstelle von new Notification('...') Push-Benachrichtigungen verwendet. Aber wenn ich es auf dem Desktop Chrom getestet, wirft es dieser Fehler

registration.showNotification is not a function 

Ist das registration.showNotification nur auf Android-Chrom, aber nicht auf dem Desktop?

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

Antwort

1

runtime.register() gibt ein JavaScript-Versprechen, das ist, warum Sie eine not a function Fehlermeldung erhalten, weil Promises keine showNotification() Methode hat.

Stattdessen müssten Sie einen Callback zu ihm ketten, um das tatsächliche registration Objekt zu erhalten (oder async/await zu verwenden, das auch cool ist).

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

Vielen Dank. Es klappt! Ich hoffe, es gibt eine Typoskript-Definition für Service-Mitarbeiter. – RedGiant