templates/website/includes/sw.html.twig line 1

Open in your IDE?
  1. <script type="text/javascript">
  2.         
  3.     async function send() {
  4.         const vapidPublicKey = '{{ swToken }}';
  5.         let urlBase64ToUint8Array = (base64String) => {
  6.             const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  7.             const base64 = (base64String + padding)
  8.               .replace(/\-/g, "+")
  9.               .replace(/_/g, "/");
  10.             const rawData = window.atob(base64);
  11.             const outputArray = new Uint8Array(rawData.length);
  12.             for (let i = 0; i < rawData.length; ++i) {
  13.               outputArray[i] = rawData.charCodeAt(i);
  14.             }
  15.             
  16.             return outputArray;
  17.         }
  18.         // Register Service Worker
  19.         const register = await navigator.serviceWorker.register(
  20.           "/sw.js",
  21.         );
  22.         {% if user %}
  23.             // Register Push
  24.             const subscription = await register.pushManager.subscribe({
  25.               userVisibleOnly: true,
  26.               applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),
  27.             });
  28.             // Send Push Notification
  29.             let sub = JSON.parse(JSON.stringify(subscription));
  30.             
  31.             if(sub && sub.keys){
  32.                 const isIOS = () => {
  33.                     return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  34.                 }
  35.                 let data = {
  36.                     endpoint: sub.endpoint,
  37.                     token: sub.keys.p256dh,
  38.                     auth: sub.keys.auth,
  39.                     platform: isIOS() ? 'ios' : 'other'
  40.                 };
  41.                 const headers = new Headers();
  42.                 headers.append("Content-Type", "application/json");
  43.                 const request = new Request("{{ path('registerNotifyAuth') }}", {
  44.                     method: "POST",
  45.                     headers: headers,
  46.                     body: JSON.stringify(data),
  47.                 });
  48.                 fetch(request).then((response) => {
  49.                     
  50.                 }).then((response) => {
  51.                 }).catch((error) => {
  52.                     console.error(error);
  53.                 });
  54.             }
  55.         {% endif %}
  56.     }
  57.     if ("serviceWorker" in navigator) {
  58.         send().catch((err) => console.error(err));
  59.     }
  60. </script>