auto update service worker and push new vue route when clicking message notification

This commit is contained in:
liamcottle
2025-02-13 20:37:29 +13:00
parent 88878af0ca
commit 0e5ee0e575
4 changed files with 45 additions and 5 deletions

View File

@@ -248,7 +248,7 @@ class Connection {
});
// show notification
await NotificationUtils.showNotification(contact.advName, message.text);
await NotificationUtils.showNewMessageNotification(contact, message.text);
}

View File

@@ -1,6 +1,8 @@
import Utils from "./Utils.js";
class NotificationUtils {
static async showNotification(title, body) {
static async showNewMessageNotification(contact, text) {
// request notification permission
const result = await Notification.requestPermission();
@@ -11,9 +13,17 @@ class NotificationUtils {
// show notification via service worker
if(navigator.serviceWorker){
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification(title, {
body: body,
registration.showNotification(contact.advName, {
body: text,
icon: "/icon.png",
data: {
"vue-route-push": {
name: "contact.messages",
params: {
publicKey: Utils.bytesToHex(contact.publicKey),
},
},
},
});
});
}

View File

@@ -52,6 +52,22 @@ for(const route of routes){
}
}
// listen for postMessage events from service worker
navigator.serviceWorker.addEventListener("message", async (event) => {
if(event.data.type === "notificationclick"){
// get notification data
const notificationData = event.data.data;
// if notification data includes vue-route-push, push the route to vue
const vueRoutePush = notificationData["vue-route-push"];
if(vueRoutePush){
await router.push(vueRoutePush);
}
}
});
createApp(App)
.use(router)
.use(vClickOutside)

View File

@@ -3,6 +3,16 @@ self.addEventListener('fetch',function() {
// it allows the browser to ask the user if they want to install to their homescreen
});
// allow service worker to install updates without waiting force existing tabs to be closed
self.addEventListener('install', (event) => {
event.waitUntil(self.skipWaiting());
});
// ensure we claim clients so the service worker can interact with them
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
// handle push notification click
self.addEventListener('notificationclick', function(event) {
@@ -12,9 +22,13 @@ self.addEventListener('notificationclick', function(event) {
// open pwa
event.waitUntil(findClient().then((client) => {
// if an existing client exists, focus it
// if an existing client exists, focus it and then send it the notification data
if(client){
client.focus();
client.postMessage({
type: "notificationclick",
data: event.notification.data,
});
return;
}