aldinokemal

WebPushNotif - Lokal Notification - index.html

Jul 24th, 2022 (edited)
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.46 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Web Push Notification</title>
  6. </head>
  7. <body>
  8. <h3>Ini contoh Web Push Notif Lokal</h3>
  9. <br>
  10. <button onclick="checkPermission()">Check Permission</button>
  11. <br>
  12. <button onclick="displayNotification()">Display Push Notif</button>
  13. <script>
  14.     function registerSW() {
  15.         if ('serviceWorker' in navigator) {   //cek browser support serviceWorker
  16.             navigator.serviceWorker
  17.                 .register('/sw.js')
  18.                 .then(function (reg) {
  19.                     //Berhasil terdaftar
  20.                     console.log('Terdaftar pada scope' + reg.scope)
  21.                 })
  22.                 .catch(function (error) {
  23.                     //Gagal Terdaftar
  24.                     console.log('Gagal :' + error)
  25.                 });
  26.         } else {
  27.             console.log('Browser tidak support SW')
  28.         }
  29.     }
  30.  
  31.     function checkPermission() {
  32.         Notification.requestPermission().then(function (permission) {
  33.             alert(permission);
  34.         });
  35.     }
  36.  
  37.     function displayNotification() {
  38.         if (Notification.permission === 'granted') {
  39.             navigator.serviceWorker.getRegistration()
  40.                 .then(reg => {
  41.                     console.log(reg)
  42.  
  43.                     const options = {
  44.                         body: 'Here is a notification body!',
  45.                         icon: 'https://miro.medium.com/max/432/1*gYmM9tPZOxnBr_sjUAgVBw.png',
  46.                         data: {url: 'https://google.com'} // allows us to identify notification
  47.                     };
  48.  
  49.                     reg.showNotification('Hello world!', options);
  50.                 });
  51.         }
  52.     }
  53.  
  54.     document.addEventListener('DOMContentLoaded', async function () {
  55.         registerSW();
  56.     });
  57. </script>
  58. </body>
  59. </html>
Add Comment
Please, Sign In to add comment