File: index.html

package info (click to toggle)
golang-github-sherclockholmes-webpush-go 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 124 kB
  • sloc: javascript: 9; makefile: 4
file content (58 lines) | stat: -rw-r--r-- 1,607 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Webpush Golang Example</title>
</head>
<body>
  <script>
    function subscribe() {
      navigator.serviceWorker.ready
        .then(function(registration) {
          const vapidPublicKey = '<YOUR_VAPID_PUBLIC_KEY>';

          return registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),
          });
        })
        .then(function(subscription) {
          console.log(
            JSON.stringify({
              subscription: subscription,
            })
          );
        })
        .catch(err => console.error(err));
    }

    function urlBase64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
      const base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');
      const rawData = window.atob(base64);
      return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
    }

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js');
      navigator.serviceWorker.ready
        .then(function(registration) {
          return registration.pushManager.getSubscription();
        })
        .then(function(subscription) {
          if (!subscription) {
            subscribe();
          } else {
            console.log(
              JSON.stringify({
                subscription: subscription,
              })
            );
          }
        });
    }
  </script>
</body>
</html>