programing tip

웹 브라우저에 푸시 알림을 보내는 방법은 무엇입니까?

itbloger 2020. 6. 1. 19:08
반응형

웹 브라우저에 푸시 알림을 보내는 방법은 무엇입니까?


Push Notification APIWeb Notification API에 대해 지난 몇 시간 동안 읽었습니다 . 또한 Google & Apple은 각각 GCM 및 APNS를 통해 무료로 푸시 알림 서비스를 제공한다는 사실을 발견했습니다.

웹 알림 API를 사용한다고 생각되는 데스크톱 알림을 사용하여 브라우저에 푸시 알림을 구현할 수 있는지 이해하려고합니다. 여기여기 Chrome에서이 작업을 수행하는 방법에 대한 Google 문서를 보았습니다 .

이제 여전히 이해할 수없는 것은 다음과 같습니다.

  1. GCM / APNS를 사용하여 Firefox 및 Safari를 포함한 모든 웹 브라우저에 푸시 알림을 보낼 수 있습니까?
  2. GCM을 통하지 않는 경우 동일한 방식으로 백엔드를 가질 수 있습니까?

하나의 답변 으로이 모든 답변이 비슷한 혼란을 겪고있는 많은 사람들을 도울 수 있다고 생각합니다.


그래서 나는 내 자신의 질문에 대답하고 있습니다. 과거에 푸시 알림 서비스를 구축 한 사람들의 모든 쿼리에 대한 답변을 받았습니다.

업데이트 (2018 년 5 월) : 다음은 Google의 웹 푸시 알림에 관한 포괄적이고 잘 작성된 문서입니다.

3 년 전의 원래 질문에 대한 답변 :

  1. GCM / APNS를 사용하여 Firefox 및 Safari를 포함한 모든 웹 브라우저에 푸시 알림을 보낼 수 있습니까?

답변 : Google은 2018 년 4 월부터 GCM을 더 이상 사용하지 않습니다. 이제 FCM ( Firebase Cloud Messaging)을 사용할 수 있습니다 . 이것은 웹 브라우저를 포함한 모든 플랫폼을 지원합니다.

  1. GCM을 통하지 않는 경우 동일한 방식으로 백엔드를 가질 수 있습니까?

답변 : 예. 푸시 알림은 자체 백엔드에서 보낼 수 있습니다. 모든 주요 브라우저에서 동일하게 지원됩니다.

구현을 더 잘 이해하려면 Google 의이 코드 랩확인하십시오 .

다양한 프로그래밍 언어로 자체 백엔드 구현 :

추가 자료 :

동일한 무료 서비스가 있습니까? 무료, 프리미엄 및 유료 모델에서 유사한 솔루션을 제공하는 회사가 있습니다. 아래에 몇 가지 목록이 있습니다.

  1. https://onesignal.com/ (무료 | 모든 플랫폼 지원)
  2. https://firebase.google.com/products/cloud-messaging/ (무료)
  3. https://clevertap.com/ (무료 플랜이 있습니다)
  4. https://goroost.com/

참고 : 무료 서비스를 선택할 때는 TOS를 읽으십시오. 무료 서비스는 종종 분석을 포함한 다양한 목적으로 사용자 데이터를 수집하여 작동합니다.

그 외에도 푸시 알림을 보내려면 HTTPS가 있어야합니다. 그러나 letsencrypt.org 를 통해 자유롭게 https를 얻을 수 있습니다.


Javier는 알림 및 현재 제한 사항을 다룹니다.

내 제안 : window.postMessage장애인 브라우저가 따라 올 때까지 기다리는 동안 Worker.postMessage()웹 작업자와 계속 작동합니다.

이는 알림 기능 테스트가 실패하거나 권한이 거부 된 경우 대화 상자 메시지 표시 처리기가 포함 된 대체 옵션 일 수 있습니다.

알림 기능 및 권한 거부 확인 :

if (!("Notification" in window) || (Notification.permission === "denied") ) {
    // use (window||Worker).postMessage() fallback ...
}

서버 측 이벤트 를 통해 서버 에서 브라우저로 데이터를 푸시 할 수 있습니다 . 이것은 본질적으로 클라이언트가 브라우저에서 "구독"할 수있는 단방향 스트림입니다. 여기에서 NotificationSSE가 브라우저로 스트리밍 될 때 객체를 만들 수 있습니다 .

var source = new EventSource('/events');

source.on('message', message => {
  var notification = new Notification(message.title, {
    body: message.body
  });
}); 

약간 오래되었지만 Eric Bidelman의이 기사 는 SSE의 기본 사항을 설명하고 일부 서버 코드 예제도 제공합니다.


GCM / APNS는 각각 Chrome과 Safari에만 해당됩니다.

나는 당신이 찾고있을 것이라고 생각합니다 Notification:

https://developer.mozilla.org/en-US/docs/Web/API/notification

It works in Chrome, Firefox, Opera and Safari.


I assume you are talking about real push notifications that can be delivered even when the user is not surfing your website (otherwise check out WebSockets or legacy methods like long polling).

Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?

GCM is only for Chrome and APNs is only for Safari. Each browser manufacturer offers its own service.

If not via GCM can we have our own back-end to do the same?

The Push API requires two backends! One is offered by the browser manufacturer and is responsible for delivering the notification to the device. The other one should be yours (or you can use a third party service like Pushpad) and is responsible for triggering the notification and contacting the browser manufacturer's service (i.e. GCM, APNs, Mozilla push servers).

Disclosure: I am the Pushpad founder


May I redefine you question as below

Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.


As of now GCM only works for chrome and android. similarly firefox and other browsers has their own api.

Now coming to the question how to implement push notification so that it will work for all common browsers with own back end.

  1. You need client side script code i.e service worker,refer( Google push notification). Though this remains same for other browsers.

2.after getting endpoint using Ajax save it along with browser name.

3.You need to create back end which has fields for title,message, icon,click URL as per your requirements. now after click on send notification, call a function say send_push(). In this write code for different browsers for example

3.1. for chrome

 $headers = array(
          'Authorization: key='.$api_key(your gcm key),
          'Content-Type: application/json',
     );
   $msg = array('to'=>'register id saved to your server');
   $url = 'https://android.googleapis.com/gcm/send';
   $ch = curl_init();

      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));

      $result = curl_exec($ch);

3.2. for mozilla

$headers = array(            
              'Content-Type: application/json',
              'TTL':6000
            );

       $url = 'https://updates.push.services.mozilla.com/wpush/v1/REGISTER_ID_TO SEND NOTIFICATION_ON';

      $ch = curl_init();

      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


      $result = curl_exec($ch);

for other browsers please google...


this is simple way to do push notification for all browser https://pushjs.org

Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
    window.focus();
    this.close();
 }
});

I suggest using pubnub. I tried using ServiceWorkers and PushNotification from the browser however, however when I tried it webviews did not support this.

https://www.pubnub.com/docs/web-javascript/pubnub-javascript-sdk

참고URL : https://stackoverflow.com/questions/33687298/how-to-send-push-notification-to-web-browser

반응형