TIL73-01 브라우저에 알림 띄우기

김태혁·2023년 4월 4일
0

TIL

목록 보기
162/205

브라우저에 알림 띄우기

  • 브라우저에 알림을 띄우는 방법은 의외로 간단하다.
  • Notification 매서드를 활용해서 브라우저에 알림을 띄우면 된다.
  • 아래 코드는 예시 코드다.
 let eventSource;
    const fetchSse = async () => {
        try {
            //EventSource생성.
            eventSource = new EventSourcePolyfill(
                `${process.env.REACT_APP_BASE_URL}api/notificaiton/`,
                {
                    headers: {
                        Authorization: `Bearer ${token}`,
                    },
                }
            );

            eventSource.onmessage = async function (event) {
                    const data = JSON.parse(event.data);
                    const message = data.message;
                    const notificationTitle = '새로운 알림이 있습니다!';
                    const notificationOptions = {
                        body: message,
                    };
                    const notification = new Notification(notificationTitle, notificationOptions);// 브라우저 알림을 띄우기 위한 Notification을 만든다.
                    console.log(notification);
                    notification.onclick = function (event) {
                      //알림 클릭 후 로직을 만들면 된다. 
                    };
                }
            };
        } catch (error) {
            console.log(error);
            if (eventSource) eventSource.close();
        }
    };
  • eventSource로 생성된 알림을 Notification 매서드에 담으면 브라우저에 알림을 띄울 수 있다.
  • 단, 브라우저 상에 알림 권한이 허용되어 있어야한다.
profile
도전을 즐기는 자

0개의 댓글