javascript - 如何从 Service Worker 发送通知

标签 javascript notifications service-worker web-notifications

我有一个服务 worker 创建了一个 Websocket 来监听通知,它工作正常。我的问题是,当我尝试显示通知时,我无法显示。这是代码

function displayNotification(title, body, tag, url, actions) {
    if (Notification.permission == "granted") {
        if (title == undefined || title == null || title == "") title = "My site"
        if (body == undefined || body == null) body = ""
        if (tag == undefined || tag == "") tag = null
        if (url == undefined || url == null || url == "") url = "https://example.com/"
        if (actions == undefined || actions == null || actions == "") actions = []

        actions.push({ action: "close", title: "Close" })

        self.ServiceWorkerRegistration.showNotification(//self.ServiceWorkerRegistration.showNotification is not a function
             title, 
            body,
            lang: "en-US",
            icon: "https://example.com/images/logo.png",
            badge: "https://example.com/images/logo.png",
            vibrate: [100, 50, 100],
            data: {
                dateOfArrival: Date.now(),
                url
            },
            timestamp: Date.now(),
            actions,
            tag
        })
    }
}

我也试过 self.showNotification()this.showNotification() 都是 null

最佳答案

我找到了答案,它是 self.registration.showNotification()。希望这对找到它的其他人有所帮助!

关于javascript - 如何从 Service Worker 发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67217488/

相关文章:

c# - 使用 MonoDroid C# 显示状态栏通知

android - 以编程方式取消(和隐藏)Android 通知

Xcode 推送通知 : APNS server for production mode

javascript - Chrome 中的 Firebase Cloud Messaging Service Worker 重定向

html - 为什么 Service Worker 只能通过 HTTPS 工作?

javascript - 在新值可用之前触发输入上的 Drop 事件

javascript - 当内容小于默认大小 (300x150) 时 iframe 调整大小

javascript - 创建动态间隔垂直线的背景

curl - 使用 GCM 推送通知发布数据

javascript - 我的正则表达式有什么问题?