IT

자바스크립트 "Web Notifications API"

아름다운전진 2023. 3. 9. 08:12
728x90

Web Notifications API는 애플리케이션이 포그라운드에 있지 않은 경우에도 웹 애플리케이션이 사용자의 데스크톱 또는 모바일 장치에 알림을 표시할 수 있도록 하는 JavaScript API입니다. 이 기능은 이메일 및 메시징 응용 프로그램에서 생산성 및 작업 관리 도구에 이르기까지 광범위한 응용 프로그램에 유용할 수 있습니다.

다음은 JavaScript에서 Web Notifications API를 사용하는 방법의 예입니다.

// Check if the browser supports notifications

if ("Notification" in window) {

// Request permission for the user to receive notifications

Notification.requestPermission().then(function (permission) {

// If the user grants permission

if (permission === "granted") {

// Create a new notification

var notification = new Notification("Hello, World!");

// Add an event listener to handle the user clicking on the notification

notification.onclick = function () {

console.log("Notification clicked!");

};

}

});

}

이 코드는 먼저 브라우저가 Web Notifications API를 지원하는지 확인한 다음 사용자에게 알림 표시 권한을 요청합니다. 사용자가 권한을 부여하면 코드는 "Hello, World!"라는 메시지와 함께 새 알림을 생성합니다. 알림을 클릭하는 사용자를 처리하기 위해 이벤트 리스너를 추가합니다.

텍스트 알림을 표시하는 것 외에도 Web Notifications API를 사용하면 알림에 아이콘, 이미지 및 기타 미디어를 포함할 수 있습니다. 예를 들면 다음과 같습니다.

// Check if the browser supports notifications

if ("Notification" in window) {

// Request permission for the user to receive notifications

Notification.requestPermission().then(function (permission) {

// If the user grants permission

if (permission === "granted") {

// Create a new notification with an icon and image

var notification = new Notification("New message", {

icon: "path/to/icon.png",

image: "path/to/image.jpg",

body: "You have a new message from John Doe",

});

// Add an event listener to handle the user clicking on the notification

notification.onclick = function () {

console.log("Notification clicked!");

};

}

});

}

이 예에서 알림에는 알림에 대한 추가 정보를 제공하는 메시지 본문뿐만 아니라 아이콘과 이미지가 포함됩니다. 이 코드는 이전 예제와 동일한 접근 방식을 사용하여 알림을 클릭하는 사용자를 처리합니다.

전반적으로 Web Notifications API는 사용자를 웹 응용 프로그램에 참여시키고 중요한 이벤트 및 업데이트에 대한 정보를 제공하는 강력한 방법을 제공합니다.

728x90