如何从服务工作者发送通知

5

我有一个服务工作者,创建了一个 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

2个回答

5
我找到了答案,它是self.registration.showNotification()。希望这可以帮助任何发现此问题的人!

1
"

Client.postMessage() may work for you:

" 可能适用于你:

service-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)
  })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接