I am virtually a baby with Promise
and serviceWorker
things, and I have no idea why this happens.
I had watched a video about Web Push and Notifications. https://youtu.be/ggUY0Q4f5ok At 1:26 of the video, it presents this code and says "You can also try this out from the browser console. Try it on the new tab page."
function displayNotification(){
if(Notification.permission === 'granted') {
navigator.serviceWorker.getRegistration()
.then(function(reg){
reg.showNotification('Hello world!');
});
}
}
I got to the new tab page and wrote the same code at the console.
But when I called displayNotification()
, it threw Uncaught (in promise) TypeError: Cannot read property 'showNotification' of undefined at <anonymous>:5:17
.
So I tried the following:
navigator.serviceWorker.getRegistration()
.then(reg=>{console.log(reg, this)});
It gave undefined Window {window: Window, self: Window, document: document, name: "", location: Location, …}
.
I guess Window
object is the result of getRegistration()
, but then what is reg
for?
Anyway, I tried the following then:
navigator.serviceWorker.getRegistration()
.then(reg=>{this.showNotification('Hello world!');});
But, it threw Uncaught (in promise) TypeError: this.showNotification is not a function at <anonymous>:2:18
Was the grammar changed, was there a wrong code in the video, or did I miss something?
Plus. I really want to develop Push API
, but I could not find any easy tutorials or quick-starts. If possible, recommend one please. Thank you so much.