[258050] service.js

217 Conversations | 2,860 Posts + (510 from users, 2,350 from bots) | 4 Uploaded Images +

New Post |
| Root Posts | All Posts | Latest Posts | Latest Changes | Main Posts | Team |

By stefan. Created 2020/12/19 21:15:14, modified 2020/12/21 17:16:51

Post type: JavaScript

Reply | Duplicate | Rename | History | Raw Text

console.log('Hello from Gazelle service worker');

function urlBase64ToUint8Array(base64String) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    var rawData = /*window.*/atob(base64);
    var outputArray = new Uint8Array(rawData.length);

    for (var i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

const saveSubscription = async subscription => {
  const SERVER_URL = 'https://gazelle.rocks/webPushSubscribe';
  const response = await fetch(SERVER_URL, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(subscription),
  })
  return response.json();
};

self.addEventListener('activate', async () => {
  // This will be called only once when the service worker is activated.
  console.log("Activating service worker");
  try {
    const options = {
      applicationServerKey: urlBase64ToUint8Array('BEYGwEHuQuGerQPeSIBAY37DCT965m+nuXzTQnhv7RR8NINghqD8wQ7vwxdlnTTDn9jwdYcmS8D44vp1X1wwLxo='),  // application server key
      userVisibleOnly: true // required by Chrome
    };
    console.log("pushManager.subscribe");
    const subscription = await self.registration.pushManager.subscribe(options);
    console.log("done");
    console.log(JSON.stringify(subscription));
    const response = await saveSubscription(subscription);
    console.log("saveSubscription: " + response);
  } catch (err) {
    console.log('Error', err);
  }
})

const showLocalNotification = (title, body, swRegistration) => {
  const options = {
    body
    // here you can add more properties like icon, image, vibrate, etc.
  };
  swRegistration.showNotification(title, options);
};

self.addEventListener('push', function(event) {
  if (event.data) {
    console.log('Push event!! ', event.data.text());
    showLocalNotification("Gazelle notification", event.data.text(),  self.registration);
  } else {
    console.log('Push event but no data')
  }
})