【问题标题】:getRegistration().then gives just undefinedgetRegistration().then 只给出 undefined
【发布时间】:2021-11-15 22:51:44
【问题描述】:

我实际上是一个拥有PromiseserviceWorker 东西的婴儿,我不知道为什么会发生这种情况。

我看过一个关于 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


    【解决方案1】:
    function displayNotification(){
        if(Notification.permission === 'granted') {
            navigator.serviceWorker.getRegistration()
            .then(function(reg){
                reg.showNotification('Hello world!');
            });
        }
    }
    

    获得原因:Uncaught (in promise) TypeError: Cannot read property 'showNotification' of undefined at <anonymous>:5:17

    是因为对 getRegistration() 的调用没有给你一个有效的结果。理想情况下,getRegistration() 应该返回一个注册对象,该对象将具有多个方法和属性,其中一个是称为 showNotification() 的方法。显然在这种情况下, getRegistration() 调用返回了其他东西?可能是 null 或 undefined 或类似的东西。您可以通过记录调用结果来进行调查,如下所示:

    function displayNotification(){
        if(Notification.permission === 'granted') {
            navigator.serviceWorker.getRegistration()
            .then(function(reg){
                console.log(reg);
            });
        }
    }
    

    问题似乎是由于您在调用 getRegistration() 之前没有注册 serviceWorking。至少我希望你在检查注册之前做这样的事情:

    navigator.serviceWorker.register('/service-worker.js');
    

    【讨论】:

    • 非常感谢。我会学习更多关于 serviceworker 的知识,并在你的帮助下注册 serviceWorker!
    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多