[英]Trigger a Client function with a service worker
我有一個聊天平台,我正在建立一個有趣的聊天平台。 我已經在平台中內置了通知。 在瀏覽器上,當您單擊通知時,它看起來像這樣,其中 noticeSource 是新消息來自的用戶。 所以它知道,聚焦頁面,然后使用loadChat()
function 加載與該用戶關聯的聊天。
note.onclick=function(){
parent.focus();
console.log(this);
loadChat(noticeSource,el);
this.close()
};
但是,我也將它作為 android 的 PWA 運行,因此當它在手機上檢測到它時,它會使用 Service Worker 的showNotification
方法。 我使用這個 function 來檢測點擊並使應用程序成為焦點。
self.addEventListener('notificationclick', function (event)
{
console.log("EVENT!",event.notification.data);
var target=event.notification.data;
const rootUrl = new URL('./index.php', location).href;
event.notification.close();
event.waitUntil(
clients.matchAll().then(matchedClients => {
for (let client of matchedClients){
console.log(client.url,rootUrl);
if (client.url.indexOf(rootUrl) >= 0){
console.log("Focus1");
return client.focus();
}
}
return clients.openWindow(rootUrl).then(
function (client) {
console.log("Focus2");
client.focus();
}
);
})
);
});
我想不通的是如何在軟件和客戶端之間進行通信,客戶端應該運行loadChat()
function 並傳遞應該運行它的用戶。 一般來說,如果有人可以向我指出一個解釋如何在軟件和客戶之間進行通信的資源,那將不勝感激。 我已經看過但沒有找到任何東西,我假設這是因為我不太清楚服務人員應該如何工作。
通常情況下,我在發布問題后找到了答案。 client
object 有一個方法postMessage()
,所以一旦我找到我的客戶端,我就可以使用它來發布帶有用戶名的消息,在客戶端我可以使用 eventListener navigator.serviceWorker.onmessage
來捕獲來自 sw 的消息並執行功能。
self.addEventListener('notificationclick', function (event)
{
console.log("EVENT!",event.notification.data);
var target=event.notification.data;
const rootUrl = new URL('./index.php', location).href;
event.notification.close();
console.log(clients);
event.waitUntil(
clients.matchAll().then(matchedClients => {
for (let client of matchedClients){
console.log(client.url,rootUrl);
if (client.url.indexOf(rootUrl) >= 0){
console.log(client);
client.focus();
client.postMessage(event.notification.data);
return ;
}
}
return clients.openWindow(rootUrl).then(
function (client) {
console.log("Focus2");
client.focus();
}
);
})
);
});
在客戶端
sw=navigator.serviceWorker;
sw.register('sw.js').then(function(registration){console.log("Scope:",registration.scope)});
sw.onmessage=function(event){
loadChat(event.data,document.getElementById(event.data));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.