【发布时间】:2021-11-15 22:51:44
【问题描述】:
我实际上是一个拥有Promise 和serviceWorker 东西的婴儿,我不知道为什么会发生这种情况。
我看过一个关于 Web 推送和通知的视频。 https://youtu.be/ggUY0Q4f5ok 在视频的 1:26 处,它显示此代码并说 “您也可以从浏览器控制台尝试此操作。在新标签页上尝试。”
function displayNotification(){
if(Notification.permission === 'granted') {
navigator.serviceWorker.getRegistration()
.then(function(reg){
reg.showNotification('Hello world!');
});
}
}
我进入新标签页并在控制台上编写了相同的代码。
但是当我打电话给displayNotification()时,它抛出了Uncaught (in promise) TypeError: Cannot read property 'showNotification' of undefined at <anonymous>:5:17。
所以我尝试了以下方法:
navigator.serviceWorker.getRegistration()
.then(reg=>{console.log(reg, this)});
它给了undefined Window {window: Window, self: Window, document: document, name: "", location: Location, …}。
我猜Window 对象是getRegistration() 的结果,但是reg 是为了什么?
无论如何,我尝试了以下方法:
navigator.serviceWorker.getRegistration()
.then(reg=>{this.showNotification('Hello world!');});
但是,它抛出了Uncaught (in promise) TypeError: this.showNotification is not a function at <anonymous>:2:18
语法是否改变了,视频中是否有错误的代码,或者我错过了什么?
另外。我真的很想开发Push API,但我找不到任何简单的教程或快速入门。如果可以,请推荐一个。非常感谢。
【问题讨论】:
标签: javascript promise push-notification notifications push-api