브라우저에 알림 띄우기
- 브라우저에 알림을 띄우는 방법은 의외로 간단하다.
- Notification 매서드를 활용해서 브라우저에 알림을 띄우면 된다.
- 아래 코드는 예시 코드다.
let eventSource;
const fetchSse = async () => {
try {
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);
console.log(notification);
notification.onclick = function (event) {
};
}
};
} catch (error) {
console.log(error);
if (eventSource) eventSource.close();
}
};
- eventSource로 생성된 알림을 Notification 매서드에 담으면 브라우저에 알림을 띄울 수 있다.
- 단, 브라우저 상에 알림 권한이 허용되어 있어야한다.