gauntface / web-push-book

Web Push Book
https://web-push-book.gauntface.com
226 stars 55 forks source link

Notification.image: Example with on-the-fly OffscreenCanvas generated image #115

Open kael opened 6 years ago

kael commented 6 years ago

cc @gauntface

Type of Issue

Suggestion of example for notification image with on-the-fly OffscreenCanvas generated image.

Details....

A code sample as a starter:

// canvas.toDataURL() not available with OffscreenCanvas ?
const toDataURL = async (data) =>
  new Promise(ok => {
    const reader = new FileReader();
    reader.addEventListener('load', () => ok(reader.result));
    reader.readAsDataURL(data);
  });

const imageCanvas = async (title) => {
  const canvas = new OffscreenCanvas(192, 192);
  const ctx = canvas.getContext('2d');
  ctx.font = "30px Comic Sans MS";
  ctx.fillStyle = "red";
  ctx.textAlign = "center";
  ctx.fillText(title, canvas.width/2, canvas.height/2);
  // Hack-ish
  const blob = await canvas.convertToBlob();
  return await toDataURL(blob);
};

self.addEventListener("push", event =>
  event.waitUntil(Promise.resolve().then(async() => {
    let body, image;
    if (self.OffscreenCanvas) image = await imageCanvas('Hello Push');
    else body = 'Your Browser does not support OffscreenCanvas with Service Worker';
    console.log('[SW]', { image });
    return self.registration.showNotification('OffscreenCanvas Demo', {
      body,
      image,
      tag: 'canvas',
    });
  }));
);