This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

요약

Web Notifications API 는 시스템 레벨에서 페이지 바깥에 알림을 보내도록 해 줍니다. 비록 어플리케이션이 유휴상태이더라도 웹앱이 사용자에게 정보를 보내도록 허용 합니다.. 한가지 분명한 사용방식은 사용자가 다른 앱을 사용하고 있을 때, 웹메일 앱이 새 이메일을 받았다고 알려 주는 것입니다.

권한 요청하기

웹 컨텐츠

앱이 알림을 보내기전에 사용자는 반드시 어플리케이션에 권한을 승인해 주어야 합니다. 이는 API가 웹페이지 외부와 상호작용 하기 위한 공통 된 조건입니다. 이로써, 사용자들에게 스팸 알림을 피할 수 있습니다.

알림을 보내는 어플리케이션은 읽기 전용 Notification.permission 속성을 통해 현재 퍼미션을 체크합니다  이는 세 가지 값을 가질 수 있습니다.

  • default: 사용자가 어떠한 권한도 부여하지 않음 (따라서 사용자에게 알림이 오지 않음)
  • granted: 사용자가 의도적으로 어플리케이션으로 부터 알람을 받도록 허가함.
  • denied: 사용자가 의도적으로 어플리케이션으로 부터 알람을 거부함.

Note: Chrome 과 Safari 는 아직 permission 속성이 구현되어 있지 않다.

만약 퍼미션이 허용되지 않았다면 어플리케이션은 사용자가 권한을 선택 할 수 있도록 Notification.requestPermission() 함수를 사용해야만 합니다. 이 메소드는 권한을 사용자가 선택한 권한을 받아오는 콜백함수를 인자로 가집니다.

아래는 앱을 초기화 하는 시점에서 권한을 요청하는 기본적인 예제 입니다:

window.addEventListener('load', function () {
  Notification.requestPermission(function (status) {
    // This allows to use Notification.permission with Chrome/Safari
    if (Notification.permission !== status) {
      Notification.permission = status;
    }
  });
});

Note: Chrome 은 load 이벤트에서 Notification.requestPermission() 함수를 호출하는 것을 허용하지 않는다. (see issue 274284).

설치된 어플리케이션

어플리케이션이 설치 되었을 때, 사용자는 application manifest 에 권한을 직접추가함으로써 알림을 피하는 것이 가능합니다. 

"permissions": {
  "desktop-notification": {
    "description": "Allows to display notifications on the user's desktop."
  }
}

알림 만들기 

 Notification 생성자를 이용하여 간단히 알림을 만들 수 있습니다. 이 생성자는 알림 시 표시되는 제목과 iconbody 와 같이 각각 아이콘, 텍스트 옵션을 인자로 가집니다.

 

A notification is displayed as soon as possible when instantiated. To track the current state of a notification, four events are triggered at the Notification instance level:

알림은 초기화 되는 대로 표시됩니다. 알림의 현재 상태를 추적하기 위해 Notification 인스턴스에서는 아래 네 가지의 이벤트를 처리합니다.

  • show: 알림이 사용자에게 표시 되는 경우.
  • click: 알림이 사용자에 의해 클릭 되는 경우.
  • close: 알림이 닫힌 경우.
  • error: 알림을 표시함에 있어 뭔가 문제가 있는 경우 (대개 어떤 무엇인가가 알림이 표시되는 것을 막은 경우 발생)

이 이벤트들은 이벤트 핸들러에 의해 처리됩니다.

onshow, onclick, onclose 또는 onerror. 이 들은 addEventListener() 메소드를 사용할 수 있습니다. Notification 역시 EventTarget 을 상속하는 메소드 이기 때문입니다. 

주의: Firefox 와 Safari 는 close 이벤트에 관련한 스펙을 따르지 않습니다. 이 스펙에서는 알림은 반드시 사용자에 의해서만 닫혀야 한다고 정의 하고 있습니다. 하지만 Firefox와 Safari 는 사용자가 알림창을 닫았음을 보증 할 수 없어 시간이 흐르면 자동으로 알림이 닫힙니다. 

스펙은 알림의 자동 닫기는 Notification.close()  메소드를 사용하는 어플리케이션 레벨에서 종료되어야 함을 명시하고 있습니다. 아래 예제를 확인해 보세요.

var n = new Notification("Hi!");

n.onshow = function () { 
  setTimeout(n.close, 5000); 
}

간단한 예제

아래와 같은 HTML 코드가 있다고 가정해봅시다.

<button>Notify me!</button>

이는 아래와 같은 방법으로 다룰 수 있습니다.

window.addEventListener('load', function () {
  // At first, let's check if we have permission for notification
  // If not, let's ask for it
  if (Notification && Notification.permission !== "granted") {
    Notification.requestPermission(function (status) {
      if (Notification.permission !== status) {
        Notification.permission = status;
      }
    });
  }

  var button = document.getElementsByTagName('button')[0];

  button.addEventListener('click', function () {
    // If the user agreed to get notified
    if (Notification && Notification.permission === "granted") {
      var n = new Notification("Hi!");
    }

    // If the user haven't tell if he want to be notified or not
    // Note: because of Chrome, we are not sure the permission property
    // is set, therefore it's unsafe to check for the "default" value.
    else if (Notification && Notification.permission !== "denied") {
      Notification.requestPermission(function (status) {
        if (Notification.permission !== status) {
          Notification.permission = status;
        }

        // If the user said okay
        if (status === "granted") {
          var n = new Notification("Hi!");
        }

        // Otherwise, we can fallback to a regular modal alert
        else {
          alert("Hi!");
        }
      });
    }

    // If the user refuse to get notified
    else {
      // We can fallback to a regular modal alert
      alert("Hi!");
    }
  });
});

실제 결과는 여기서 확인 해 보세요.

반복 알림 다루기

너무 많은 알림이 발생하는 경우 사용자가 괴로울 수 있습니다. 예를 들어, 문자 메시지 앱이 메시지가 올 때마다 알림을 한다고 해보겠습니다. 수백개의 불필요한 알림을 피하기 위해 대기중인 알림 큐를 활용하는 방법이 있습니다.

이렇게 하려면 새로운 알림에 태그를 추가하면 됩니다. 만약에 알림이 같은 태그를 가졌는데 아직 표시 되기 전이라면, 새 알림은 이전의 알림을 대체하게 됩니다. 만약에 태그가 같고 이미 표시가 되었다면 이전 알림은 닫히고 새로운 알림이 표시 됩니다.

태그 예제

아래와 같은 HTML 코드가 있다고 하겠습니다.

<button>Notify me!</button>

아래와 같은 방법으로 다수의 알림을 다룰 수가 있습니다.

window.addEventListener('load', function () {
  // At first, let's check if we have permission for notification
  // If not, let's ask for it
  if (Notification && Notification.permission !== "granted") {
    Notification.requestPermission(function (status) {
      if (Notification.permission !== status) {
        Notification.permission = status;
      }
    });
  }

  var button = document.getElementsByTagName('button')[0];

  button.addEventListener('click', function () {
    // If the user agreed to get notified
    // Let's try to send ten notification
    if (Notification && Notification.permission === "granted") {
      for (var i = 0; i < 10; i++) {
        // Thanks to the tag, we should only see the "Hi! 10" notification
        var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
      }
    }

    // If the user haven't tell if he want to be notified or not
    // Note: because of Chrome, we are not sure the permission property
    // is set, therefore it's unsafe to check for the "default" value.
    else if (Notification && Notification.permission !== "denied") {
      Notification.requestPermission(function (status) {
        if (Notification.permission !== status) {
          Notification.permission = status;
        }

        // If the user said okay
        if (status === "granted") {
          for (var i = 0; i < 10; i++) {
            // Thanks to the tag, we should only see the "Hi! 10" notification
            var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
          }
        }

        // Otherwise, we can fallback to a regular modal alert
        else {
          alert("Hi!");
        }
      });
    }

    // If the user refuse to get notified
    else {
      // We can fallback to a regular modal alert
      alert("Hi!");
    }
  });
});

실제 결과를 확인 해 보세요.

명세

Specification Status Comment
Notifications API Living Standard Initial specification.

브라우저 호환

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support 22
Notes
Full support 22
Notes
Notes Before Chrome 22, the support for notification followed an old prefixed version of the specification and used the navigator.webkitNotifications object to instantiate a new notification. Before Chrome 32, Notification.permission was not supported. Before Chrome 42, service worker additions were not supported. Starting in Chrome 49, notifications do not work in incognito mode.
Full support 5
Prefixed
Prefixed Implemented with the vendor prefix: -webkit-
Edge Full support YesFirefox Full support 22
Full support 22
Full support 4
Prefixed
Prefixed Implemented with the vendor prefix: -moz-
IE No support NoOpera Full support 25Safari Full support 6WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support 22
Full support 22
Full support 4
Prefixed
Prefixed Implemented with the vendor prefix: -webkit-
Opera Android Full support YesSafari iOS No support NoSamsung Internet Android ?
Available in workersChrome Full support 45Edge Full support YesFirefox Full support 41IE No support NoOpera Full support 32Safari ? WebView Android No support NoChrome Android Full support 45Edge Mobile Full support YesFirefox Android Full support 41Opera Android Full support 32Safari iOS No support NoSamsung Internet Android ?
Secure contexts onlyChrome Full support 62Edge ? Firefox ? IE No support NoOpera Full support 49Safari ? WebView Android No support NoChrome Android Full support 62Edge Mobile ? Firefox Android ? Opera Android Full support 49Safari iOS No support NoSamsung Internet Android ?
Notification() constructorChrome Full support 22
Full support 22
Full support 5
Prefixed
Prefixed Implemented with the vendor prefix: webkit
Edge Full support YesFirefox Full support 22
Full support 22
Full support 4
Prefixed
Prefixed Implemented with the vendor prefix: moz
IE No support NoOpera Full support 25Safari Full support 6WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support 22
Full support 22
Full support 4
Prefixed
Prefixed Implemented with the vendor prefix: moz
Opera Android Full support YesSafari iOS No support NoSamsung Internet Android ?
actionsChrome Full support 53Edge Full support 18Firefox No support NoIE No support NoOpera Full support 39Safari ? WebView Android No support NoChrome Android Full support 53Edge Mobile No support NoFirefox Android No support NoOpera Android Full support 39Safari iOS No support NoSamsung Internet Android ?
badgeChrome Full support 53Edge Full support 18Firefox No support NoIE No support NoOpera Full support 39Safari ? WebView Android No support NoChrome Android Full support 53Edge Mobile No support NoFirefox Android No support NoOpera Android Full support 39Safari iOS No support NoSamsung Internet Android ?
bodyChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
dataChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
dirChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
iconChrome Full support 22
Full support 22
Full support 5
Prefixed
Prefixed Implemented with the vendor prefix: -webkit-
Edge ? Firefox Full support 22
Full support 22
Full support 4
Prefixed
Prefixed Implemented with the vendor prefix: -moz-
IE No support NoOpera Full support 25Safari No support NoWebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support 22
Full support 22
Full support 4
Prefixed
Prefixed Implemented with the vendor prefix: -moz-
Opera Android Full support YesSafari iOS No support NoSamsung Internet Android ?
imageChrome Full support 53Edge Full support 18Firefox No support NoIE No support NoOpera Full support 40Safari ? WebView Android No support NoChrome Android Full support 53Edge Mobile ? Firefox Android No support NoOpera Android Full support 40Safari iOS No support NoSamsung Internet Android ?
langChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
maxActionsChrome Full support YesEdge Full support 18Firefox No support NoIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android No support NoOpera Android ? Safari iOS No support NoSamsung Internet Android ?
onclickChrome Full support YesEdge ? Firefox No support NoIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android No support NoOpera Android ? Safari iOS No support NoSamsung Internet Android ?
oncloseChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
onerrorChrome Full support YesEdge ? Firefox No support NoIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android No support NoOpera Android ? Safari iOS No support NoSamsung Internet Android ?
onshowChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
permissionChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
renotifyChrome Full support 50Edge No support NoFirefox No support NoIE No support NoOpera Full support 37Safari No support NoWebView Android No support NoChrome Android Full support 50Edge Mobile No support NoFirefox Android No support NoOpera Android Full support 37Safari iOS No support NoSamsung Internet Android ?
requireInteractionChrome Full support YesEdge Full support 17Firefox No support NoIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile No support NoFirefox Android No support NoOpera Android ? Safari iOS No support NoSamsung Internet Android ?
silentChrome Full support 43Edge Full support 17Firefox No support NoIE No support NoOpera Full support 30Safari No support NoWebView Android No support NoChrome Android Full support 43Edge Mobile No support NoFirefox Android No support NoOpera Android Full support 30Safari iOS No support NoSamsung Internet Android ?
tagChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
timestampChrome Full support YesEdge Full support 17Firefox No support NoIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile No support NoFirefox Android No support NoOpera Android ? Safari iOS No support NoSamsung Internet Android ?
titleChrome Full support YesEdge ? Firefox No support NoIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android No support NoOpera Android ? Safari iOS No support NoSamsung Internet Android ?
vibrateChrome Full support 53Edge No support NoFirefox No support NoIE No support NoOpera Full support 39Safari ? WebView Android No support NoChrome Android Full support 53Edge Mobile No support NoFirefox Android No support NoOpera Android Full support 39Safari iOS No support NoSamsung Internet Android ?
closeChrome Full support YesEdge ? Firefox Full support YesIE No support NoOpera ? Safari ? WebView Android No support NoChrome Android Full support YesEdge Mobile ? Firefox Android Full support YesOpera Android ? Safari iOS No support NoSamsung Internet Android ?
requestPermissionChrome Full support 46Edge ? Firefox Full support 47IE No support NoOpera Full support 40Safari ? WebView Android No support NoChrome Android Full support 46Edge Mobile ? Firefox Android Full support YesOpera Android Full support 40Safari iOS No support NoSamsung Internet Android ?

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.
Requires a vendor prefix or different name for use.
Requires a vendor prefix or different name for use.

See also

문서 태그 및 공헌자

이 페이지의 공헌자: oohii, junho85
최종 변경자: oohii,