40 lines
1.6 KiB
JavaScript
40 lines
1.6 KiB
JavaScript
self.addEventListener("push", (event) => {
|
|
if (!event.data) return;
|
|
|
|
const payload = event.data.json();
|
|
if (payload.type !== "message") return;
|
|
|
|
const channel = payload.data && payload.data.channel ? payload.data.channel : {};
|
|
const isInGuild = channel.type === "GUILD_TEXT" || channel.type === "GUILD_VOICE";
|
|
|
|
const channelType = isInGuild ? (channel.type === "GUILD_TEXT" ? "Text" : "Voice") : "";
|
|
const title = `${payload.data && payload.data.author ? payload.data.author : "Unknown"}${isInGuild ? ` (#${channel.name}, ${channelType} Channels)` : ""}`;
|
|
|
|
const options = {
|
|
body: payload.data && payload.data.content ? payload.data.content : "",
|
|
icon: payload.data && payload.data.avatar ? payload.data.avatar : null,
|
|
tag: `channel-${channel.id}`,
|
|
data: { channelId: channel.id, isInGuild },
|
|
};
|
|
|
|
event.waitUntil(self.registration.showNotification(title, options));
|
|
});
|
|
|
|
self.addEventListener("notificationclick", (event) => {
|
|
event.notification.close();
|
|
|
|
const payload = event.notification.data;
|
|
const targetUrl = `/channels/${!payload.isInGuild ? "@me/" : ""}${payload.channelId}` || "/";
|
|
|
|
event.waitUntil(
|
|
clients.matchAll({ type: "window", includeUncontrolled: true }).then((clientList) => {
|
|
for (let i = 0; i < clientList.length; i++) {
|
|
const client = clientList[i];
|
|
if (client.url === targetUrl && "focus" in client) {
|
|
return client.focus();
|
|
}
|
|
}
|
|
return clients.openWindow(targetUrl);
|
|
})
|
|
);
|
|
}); |