簡體   English   中英

如何從服務人員發送通知

[英]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()可能對您有用:

服務工作者.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() 希望這可以幫助其他找到這個的人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM