728x90

Push API는 웹사이트가 열려 있지 않은 경우에도 웹사이트가 서버에서 푸시 알림을 받을 수 있도록 하는 JavaScript API입니다. 푸시 알림은 사용자의 장치로 전송되는 메시지이며 사용자가 웹사이트나 애플리케이션을 적극적으로 사용하지 않는 경우에도 표시될 수 있습니다.

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

// First, check if the browser supports the Push API

if ('PushManager' in window) {

// Request permission to show notifications

Notification.requestPermission().then(permission => {

if (permission === 'granted') {

// Register a service worker to handle push notifications

navigator.serviceWorker.register('service-worker.js').then(() => {

console.log('Service worker registered');

 

// Get a push subscription from the server

return navigator.serviceWorker.ready.then(serviceWorkerRegistration => {

return serviceWorkerRegistration.pushManager.subscribe({

userVisibleOnly: true,

applicationServerKey: urlBase64ToUint8Array('your-public-key')

});

});

}).then(subscription => {

console.log('Push subscription successful');

 

// Send the subscription to the server to store it for later use

fetch('/subscribe', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({

subscription: subscription

})

}).then(() => {

console.log('Subscription sent to server');

}).catch(error => {

console.error('Error sending subscription to server:', error);

});

}).catch(error => {

console.error('Error registering service worker:', error);

});

} else {

console.error('Permission to show notifications denied');

}

});

} else {

console.error('Push notifications not supported');

}

// Convert a base64-encoded string to a Uint8Array

function urlBase64ToUint8Array(base64String) {

const padding = '='.repeat((4 - base64String.length % 4) % 4);

const base64 = (base64String + padding)

.replace(/\-/g, '+')

.replace(/_/g, '/');

const rawData = window.atob(base64);

const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {

outputArray[i] = rawData.charCodeAt(i);

}

return outputArray;

}

이 코드는 다음을 수행합니다.

  1. 브라우저가 Push API를 지원하는지 확인합니다.
  2. 알림을 표시하려면 사용자에게 권한을 요청합니다.
  3. 푸시 알림을 처리할 서비스 워커를 등록합니다.
  4. 서버에서 푸시 구독을 가져옵니다.
  5. 나중에 사용할 수 있도록 저장하기 위해 구독을 서버로 보냅니다.

`urlBase64ToUint8Array` 함수는 base64로 인코딩된 문자열을 `pushManager.subscribe` 메서드의 `applicationServerKey` 속성에 필요한 Uint8Array로 변환하는 데 사용됩니다.

구독이 서버에 저장되면 서버는 올바른 장치를 대상으로 하는 구독을 사용하여 사용자의 장치에 푸시 알림을 보낼 수 있습니다.

728x90

+ Recent posts