Codelab: 푸시 알림 클라이언트 빌드

Kate Jeffreys
Kate Jeffreys
Kayce Basques
Kayce Basques

이 Codelab에서는 푸시 알림 클라이언트를 빌드하는 방법을 단계별로 보여줍니다. Codelab을 마치면 다음을 수행하는 클라이언트가 생성됩니다.

  • 사용자를 푸시 알림에 구독시킵니다.
  • 푸시 메시지를 수신하고 알림으로 표시합니다.
  • 사용자의 푸시 알림을 수신 거부합니다.

이 Codelab은 실습을 통해 학습하는 데 중점을 두며 개념에 관해서는 많이 다루지 않습니다. 푸시 작동 방식을 읽고 푸시 알림 개념을 알아보세요.

이 Codelab의 서버 코드는 이미 완료되어 있습니다. 이 Codelab에서는 클라이언트만 구현합니다. 푸시 알림 서버를 구현하는 방법을 알아보려면 Codelab: 푸시 알림 서버 빌드를 확인하세요.

브라우저 호환성

이 Codelab은 다음 운영체제 및 브라우저 조합에서 작동하는 것으로 알려져 있습니다.

  • Windows: Chrome, Edge
  • macOS: Chrome, Firefox
  • Android: Chrome, Firefox

이 Codelab은 다음 운영체제(또는 운영체제와 브라우저 조합)에서 작동하지 않는 것으로 알려져 있습니다.

  • macOS: Brave, Edge, Safari
  • iOS

설정

리믹스하여 수정을 클릭하여 프로젝트를 수정할 수 있도록 합니다.

인증 설정

푸시 알림을 작동시키려면 인증 키를 사용하여 서버와 클라이언트를 설정해야 합니다. 이유는 웹 푸시 프로토콜 요청 서명을 참고하세요. 일반적으로 다음과 같이 .env 파일에 보안 비밀을 저장합니다.

VAPID_PUBLIC_KEY="BKiwTvD9HA…" VAPID_PRIVATE_KEY="4mXG9jBUaU…" VAPID_SUBJECT="mailto:[email protected]" 
  1. public/index.js를 엽니다.
  2. VAPID_PUBLIC_KEY_VALUE_HERE을 공개 키 값으로 바꿉니다.

서비스 워커 등록

클라이언트가 알림을 수신하고 표시하려면 서비스 워커가 필요합니다. 서비스 워커는 가능한 한 빨리 등록하는 것이 좋습니다. 자세한 내용은 푸시된 메시지를 알림으로 수신 및 표시를 참고하세요.

  1. // TODO add startup logic here 주석을 다음 코드로 바꿉니다.

    if ('serviceWorker' in navigator && 'PushManager' in window) {   navigator.serviceWorker.register('./service-worker.js').then(serviceWorkerRegistration => {     console.info('Service worker was registered.');     console.info({serviceWorkerRegistration});   }).catch(error => {     console.error('An error occurred while registering the service worker.');     console.error(error);   });   subscribeButton.disabled = false; } else {   console.error('Browser does not support service workers or push messages.'); }  subscribeButton.addEventListener('click', subscribeButtonHandler); unsubscribeButton.addEventListener('click', unsubscribeButtonHandler); 
  2. Chrome에서 DevTools 콘솔을 엽니다.

  3. Service worker was registered. 메시지가 콘솔에 로깅됩니다.

푸시 알림 권한 요청

페이지 로드 시 푸시 알림을 보낼 권한을 요청해서는 안 됩니다. 대신 UI에서 사용자에게 푸시 알림을 수신할지 묻습니다. 사용자가 명시적으로 확인 (예: 버튼 클릭)하면 브라우저에서 푸시 알림 권한을 얻기 위한 공식 절차를 시작할 수 있습니다.

  1. public/index.js에서 subscribeButtonHandler()// TODO 주석을 다음 코드로 바꿉니다.

    // Prevent the user from clicking the subscribe button multiple times. subscribeButton.disabled = true; const result = await Notification.requestPermission(); if (result === 'denied') {   console.error('The user explicitly denied the permission request.');   return; } if (result === 'granted') {   console.info('The user accepted the permission request.'); } 
  2. 앱 탭으로 돌아가서 푸시 구독을 클릭합니다. 브라우저 또는 운영체제에서 웹사이트가 푸시 알림을 전송하도록 허용할지 묻습니다.

  3. 허용 (또는 브라우저나 운영체제에서 사용하는 해당 문구)을 선택합니다. 콘솔에 요청이 수락되었는지 거부되었는지 나타내는 메시지가 표시됩니다.

푸시 알림 구독

구독 프로세스에는 푸시 서비스라고 하는 브라우저 공급업체에서 제어하는 웹 서비스와의 상호작용이 포함됩니다. 푸시 알림 구독 정보를 가져오면 서버로 전송하여 서버가 데이터베이스에 장기적으로 저장하도록 해야 합니다.

  1. 다음 강조 표시된 코드를 subscribeButtonHandler()에 추가합니다.

    subscribeButton.disabled = true; const result = await Notification.requestPermission(); if (result === 'denied') {   console.error('The user explicitly denied the permission request.');   return; } if (result === 'granted') {   console.info('The user accepted the permission request.'); } const registration = await navigator.serviceWorker.getRegistration(); const subscribed = await registration.pushManager.getSubscription(); if (subscribed) {   console.info('User is already subscribed.');   notifyMeButton.disabled = false;   unsubscribeButton.disabled = false;   return; } const subscription = await registration.pushManager.subscribe({   userVisibleOnly: true,   applicationServerKey: urlB64ToUint8Array(VAPID_PUBLIC_KEY) }); notifyMeButton.disabled = false; fetch('/add-subscription', {   method: 'POST',   headers: {     'Content-Type': 'application/json'   },   body: JSON.stringify(subscription) }); 

userVisibleOnly 옵션은 true여야 합니다. 언젠가는 사용자에게 표시되는 알림(무음 푸시)을 표시하지 않고 메시지를 푸시할 수 있을지도 모르지만, 개인 정보 보호 문제로 인해 브라우저에서는 이 기능을 허용하지 않습니다.

applicationServerKey 값은 base64 문자열을 Uint8Array로 변환하는 유틸리티 함수를 사용합니다. 이 값은 서버와 푸시 서비스 간의 인증에 사용됩니다.

푸시 알림 수신 거부

사용자가 푸시 알림을 구독한 후 사용자가 마음을 바꿔 더 이상 푸시 알림을 수신하지 않으려는 경우를 대비해 UI에서 구독 취소 방법을 제공해야 합니다.

  • unsubscribeButtonHandler()// TODO 주석을 다음 코드로 바꿉니다.
const registration = await navigator.serviceWorker.getRegistration(); const subscription = await registration.pushManager.getSubscription(); fetch('/remove-subscription', {   method: 'POST',   headers: {     'Content-Type': 'application/json'   },   body: JSON.stringify({endpoint: subscription.endpoint}) }); const unsubscribed = await subscription.unsubscribe(); if (unsubscribed) {   console.info('Successfully unsubscribed from push notifications.');   unsubscribeButton.disabled = true;   subscribeButton.disabled = false;   notifyMeButton.disabled = true; } 

푸시 메시지를 수신하고 알림으로 표시

앞서 언급했듯이 서버에서 클라이언트로 푸시된 메시지의 수신 및 표시를 처리하려면 서비스 워커가 필요합니다. 자세한 내용은 푸시된 메시지를 알림으로 수신 및 표시를 참고하세요.

  1. public/service-worker.js를 열고 서비스 워커의 push 이벤트 핸들러에 있는 // TODO 주석을 다음 코드로 바꿉니다.

    let data = event.data.json(); const image = 'logo.png'; const options = {   body: data.options.body,   icon: image } self.registration.showNotification(   data.title,   options ); 
  2. 앱 탭으로 돌아갑니다.

  3. 알림 받기를 클릭합니다. 푸시 알림이 표시됩니다.

  4. 지원되는 다른 브라우저에서 앱 탭의 URL을 엽니다. 구독 워크플로를 진행하고 모두에게 알림을 클릭합니다. 각각 동일한 푸시 알림이 표시됩니다.

다양한 방법으로 알림을 맞춤설정할 수 있습니다. 자세한 내용은 ServiceWorkerRegistration.showNotification()의 매개변수를 참고하세요.

사용자가 알림을 클릭할 때 URL 열기

실제로는 알림을 사용하여 사용자의 재참여를 유도하고 사이트를 방문하도록 유도할 수 있습니다. 이렇게 하려면 서비스 워커를 좀 더 구성해야 합니다.

  1. 서비스 워커의 notificationclick 이벤트 핸들러에서 // TODO 주석을 다음 코드로 바꿉니다.

    event.notification.close(); event.waitUntil(self.clients.openWindow('https://web.dev')); 
  2. 앱 탭으로 돌아가서 다른 알림을 자신에게 보내고 알림을 클릭합니다. 브라우저에서 새 탭을 열고 https://web.dev을 로드해야 합니다.

다음 단계