알림 API 사용

어니스트 델가도
어니스트 델가도

소개

Notifications API를 사용하면 포커스가 있는 탭과 관계없이 특정 이벤트에 대한 알림을 수동적으로 (새 이메일, 트윗, 캘린더 이벤트) 사용자와 사용자 상호작용에 모두 표시할 수 있습니다. 초안 사양이 있지만 현재 표준이 아닙니다.

다음과 같은 간단한 단계에 따라 몇 분 만에 알림을 구현할 수 있습니다.

1단계: Notifications API 지원 확인

webkitNotifications가 지원되는지 확인합니다. webkitNotifications의 이름은 초안 사양의 일부이기 때문입니다. 최종 사양에는 대신 notifications() 함수가 있습니다.

// check for notifications support
// you can omit the 'window' keyword
if (window.webkitNotifications) {
console.log("Notifications are supported!");
}
else {
console.log("Notifications are not supported for this Browser/OS version yet.");
}

2단계: 사용자가 웹사이트에 알림을 표시하도록 권한을 부여하도록 허용하기

앞서 언급한 생성자는 사용자가 알림을 표시할 권한을 웹사이트에 수동으로 부여하지 않은 경우 보안 오류를 발생시킵니다. 예외를 처리하려면 try-catch 문을 사용할 수 있지만 같은 목적으로 checkPermission 메서드를 사용할 수도 있습니다.

document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
window.webkitNotifications.createNotification(
    'icon.png', 'Notification Title', 'Notification content...');
} else {
window.webkitNotifications.requestPermission();
}
}, false);

웹 애플리케이션에 알림을 표시할 권한이 없으면 requestPermission 메서드가 정보 표시줄을 표시합니다.

Chrome의 알림 권한 정보 표시줄
Chrome의 알림 권한 정보 표시줄

그러나 요청하지 않은 정보 표시줄을 방지하기 위해 requestPermission 메서드는 마우스 또는 키보드 이벤트와 같은 사용자 작업에 의해 트리거되는 이벤트 핸들러에서만 작동한다는 점에 매우 중요합니다. 이 경우 사용자 작업은 ID가 'show_button'인 버튼을 클릭하는 것입니다. 사용자가 특정 시점에 requestPermission를 트리거하는 버튼이나 링크를 명시적으로 클릭하지 않은 경우 위 스니펫은 작동하지 않습니다.

3단계: 리스너 및 기타 작업 연결하기

document.querySelector('#show_button').addEventListener('click', function() {
  if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
    // function defined in step 2
    notification_test = window.webkitNotifications.createNotification(
      'icon.png', 'Notification Title', 'Notification content...');
    notification_test.ondisplay = function() { ... do something ... };
    notification_test.onclose = function() { ... do something else ... };
    notification_test.show();
  } else {
    window.webkitNotifications.requestPermission();
  }
}, false);

이 시점에서 이러한 모든 이벤트와 작업을 캡슐화하여 자체 알림 클래스를 만들어 코드를 더 깔끔하게 유지하는 것이 좋습니다. 그러나 이 내용은 이 튜토리얼에서 다루지 않습니다.