Notifications API

별상자·2024년 11월 1일
post-thumbnail

Notifications API는 웹에서 사용자에게 알림을 보내는 API이다.
문서에 위처럼 적혀있어 처음에는 푸쉬알림도 되는지 기대했지만 어림도 없었다.

Notifications API는 웹 브라우저 내에서만 동작하는 알림 메세지이다.
따라서 웹 브라우저가 종료되거나 백그라운드로 전환될 경우 동작하지 않는다.
동작 예시는 아래 블로그의 테스트 영상을 참고하기 바란다.

Notifications API

사용법은 어렵지 않고 아래와 같다.
권한 요청

if ('Notification' in window) {
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      console.log('Notification permission granted');
    } else {
      console.log('Notification permission denied');
    }
  });
} else {
  console.log('Notifications API is not supported by this browser.');
}

알림 생성

function showNotification() {
  if (Notification.permission === 'granted') {
    const notification = new Notification('New Message!', {
      body: 'You have a new message from ChatApp.',
      icon: 'message-icon.png',
      tag: 'new-message' // 알림 중복 방지 태그
    });

    // 알림 클릭 이벤트
    notification.onclick = () => {
      window.open('https://yourapp.com/messages');
    };
  }
}

어떻게 활용할까?

단순히 Notification만 사용한다면 환경이 제한적이지만 이를 이전 장에서 다루었던 서비스 워커와 결합하여 PWAs로 개발하면 모바일 푸쉬기능을 사용할 수 있다.
해당 내용은 PWAs와 서비스워커를 다룬 글과 공식문서를 참고하기 바란다.

공식문서

Notifications API

profile
알고, 사용하고, 개선하기

0개의 댓글