멈멈-토이프로젝트(next.js)2

nextj PWA 설정 하기 2차

순9 2024. 10. 2. 17:18
728x90

가이드에 나와 있는

https://whatpwacando.today/

 

What PWA Can Do Today

A showcase of what is possible with Progressive Web Apps today.

whatpwacando.today

링크에서 알림 관련 코드 사용

 

const notification = document.querySelector('#notification');
const sendButton = document.querySelector('#send');
const registration = await navigator.serviceWorker.getRegistration();

const sendNotification = async () => {
  if(Notification.permission === 'granted') {
    showNotification(notification.value);
  }
  else {
    if(Notification.permission !== 'denied') {
      const permission = await Notification.requestPermission();
  
      if(permission === 'granted') {
        showNotification(notification.value);
      }
    }
  }
  };
  
  const showNotification = body => {
  const title = 'What PWA Can Do Today';
  
  const payload = {
    body
  };
  
  if('showNotification' in registration) {
    registration.showNotification(title, payload);
  }
  else {
    new Notification(title, payload);
  }
};

sendButton.addEventListener('click', sendNotification);

이 코드를 nextjs 에서 사용 할 수 있도록 수정

 

 async function sendNotification() {
    const registration = await navigator.serviceWorker.getRegistration();

    // registration이 undefined가 아닐 경우에만 showNotification 호출
    if (Notification.permission === 'granted' && registration) {
      showNotification(message, registration);
    } else {
      if (Notification.permission !== 'denied') {
        const permission = await Notification.requestPermission();
        if (permission === 'granted' && registration) {
          showNotification(message, registration);
        }
      }
    }
}

  const showNotification = (body: string, registration: ServiceWorkerRegistration) => {
    const title = 'What PWA Can Do Today';
    const payload = {
      body,
      icon: '/icon/1.png',
    };

    if ('showNotification' in registration) {
      registration.showNotification(title, payload);
    } else {
      new Notification(title, payload);
    }
  };

  if (!isSupported) {
    return <p>Push notifications are not supported in this browser.</p>
  }