Skip to content

Instantly share code, notes, and snippets.

@AimWhy
Last active February 28, 2025 13:42
Show Gist options
  • Select an option

  • Save AimWhy/3e3e133fc1aae9b4ce0fc5340d345b89 to your computer and use it in GitHub Desktop.

Select an option

Save AimWhy/3e3e133fc1aae9b4ce0fc5340d345b89 to your computer and use it in GitHub Desktop.

Revisions

  1. AimWhy renamed this gist Feb 28, 2025. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. AimWhy created this gist Feb 28, 2025.
    53 changes: 53 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    "use strict";

    self.addEventListener('install', (event) => {
    event.waitUntil(self.skipWaiting());
    });

    self.addEventListener('activate', (event) => {
    event.waitUntil(self.clients.claim());
    });

    self.addEventListener('message', (event) => {
    switch (event.data.type) {
    case "broadcast":
    const message = event.data;
    message.sender_id = event.source.id;

    event.waitUntil(messageClients(message));
    break;
    default:
    console.info("Service Worker: unknown message", event);
    }
    });

    self.addEventListener("notificationclick", (event) => {
    const notification = event.notification;
    const localURL = ensureLocalURL(notification.data ? notification.data.url : void 0);
    event.waitUntil(focusWindow(localURL));
    });

    // Relay a message to all clients (including the sender)
    function messageClients(message) {
    return self.clients.matchAll().then((clientList) => {
    clientList.forEach((client) => {
    client.postMessage(message);
    })
    });
    }

    // Try to focus a tab with the given url. When such a tab is not found, a new one will be opened.
    function focusWindow(url) {
    return clients.matchAll({ type: "window" }).then((clientList) => {
    // Check if there already is a tab with has this url open.
    for (const client of clientList) {
    if ((client.url === url) && ('focus' in client)) {
    return client.focus();
    }
    }

    if (clients.openWindow) {
    return clients.openWindow(url);
    }
    });
    }