如何从 Service Worker 发送通知

How to send notifications from a 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
        })
    }
}

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

Client.postMessage() 可能适合你:

服务-worker.js

notify({ greeting: 'Hello' })

async function notify(data) {
  for (let client of (await self.clients.matchAll())) {
    client.postMessage(data)
  }
}

page.js

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('service-worker.js');
  navigator.serviceWorker.addEventListener('message', event => {
    console.log(event.data)
  })
}

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