[258044] Service Worker Test

219 Conversations | 2,863 Posts + (510 from users, 2,353 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:13:37, modified 2020/12/21 17:18:00

Post type: JavaX Code (HTML Bot)

Show as HTML page | Reply | Duplicate | Rename | History | Raw Text | Talk to this bot | Show Java transpilation

hhtml_title_body("Service Worker Test",
  loadJQuery2()
  + h1("Service Worker Test")
  + hjs([[
    const check = () => {
      if (!('serviceWorker' in navigator)) {
        throw new Error('No Service Worker support!')
      }
      if (!('PushManager' in window)) {
        throw new Error('No Push API Support!')
      }
    };
    
    const requestNotificationPermission = async () => {
      const permission = await window.Notification.requestPermission()
      // value of permission can be 'granted', 'default', 'denied'
      // granted: user has accepted the request
      // default: user has dismissed the notification permission popup by clicking on x
      // denied: user has denied the request.
      if (permission !== 'granted') {
        throw new Error('Permission not granted for Notification')
      }
    };
    
    const registerServiceWorker = async () => {
      const swRegistration = await navigator.serviceWorker.register('/text/258050?ct=text/javascript', {scope: '/'});
      return swRegistration;
    };
    
    const showLocalNotification = (title, body, swRegistration) => {
      swRegistration.showNotification(title, { body });
    }
    
    const main = async () => {
      check();
      const swRegistration = await registerServiceWorker();
      console.log("Service worker registered: " + swRegistration);
      const permission = await requestNotificationPermission();
      console.log("Notification permission: " + permission);
      //showLocalNotification('Demo notification', 'Hello user', swRegistration);
    };
  
    main();
  ]]))

Referenced by posts (latest first):