如何从 Service Worker 发送通知

Kal*_*ale 5 javascript notifications web-notifications service-worker

我有一个 Service 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
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过self.showNotification()this.showNotification()两者都是空的

Kal*_*ale 5

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