Javascript 如何向网络浏览器发送推送通知?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33687298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:21:15  来源:igfitidea点击:

How to send push notification to web browser?

javascriptgoogle-cloud-messagingweb-notificationsweb-pushpush-api

提问by esafwan

I have been reading for past few hours about Push Notification APIand Web Notification API. I also discovered that Google & Apple gives push notification service for free via GCM and APNS respectively.

过去几个小时我一直在阅读有关Push Notification APIWeb Notification API 的内容。我还发现谷歌和苹果分别通过 GCM 和 APNS 免费提供推送通知服务。

I am trying to understand if we can implement push notification to browsers using Desktop Notification, which I believe is what Web Notification API does. I saw a google documentation on how this can be done for Chrome here& here.

我试图了解我们是否可以使用桌面通知向浏览器实现推送通知,我认为这就是 Web Notification API 所做的。我在此处此处看到了有关如何为 Chrome 完成此操作的 google 文档。

Now what am still not able to understand is:

现在我仍然无法理解的是:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?
  2. If not via GCM can we have our own back-end to do the same?
  1. 我们可以使用 GCM/APNS 向包括 Firefox 和 Safari 在内的所有 Web 浏览器发送推送通知吗?
  2. 如果不是通过 GCM,我们可以有自己的后端来做同样的事情吗?

I believe all these answered in one answer can help a lot of people who are having similar confusions.

我相信所有这些在一个答案中得到的回答可以帮助很多有类似困惑的人。

采纳答案by esafwan

So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.

所以在这里我回答我自己的问题。我已经从过去构建推送通知服务的人那里得到了所有问题的答案。

Update (May 2018):Here is acomprehensive and a very well written doc on web push notification from Google.

更新(2018 年 5 月):这是一篇关于 Google 网络推送通知全面且写得很好的文档。

Answer to the original questions asked 3 years ago:

回答 3 年前提出的原始问题:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?
  1. 我们可以使用 GCM/APNS 向包括 Firefox 和 Safari 在内的所有 Web 浏览器发送推送通知吗?

Answer:Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging(FCM). This supports all platforms including web browsers.

答:自 2018 年 4 月起,Google 已弃用 GCM。您现在可以使用Firebase Cloud Messaging(FCM)。这支持所有平台,包括网络浏览器。

  1. If not via GCM can we have our own back-end to do the same?
  1. 如果不是通过 GCM,我们可以有自己的后端来做同样的事情吗?

Answer:Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.

答:是的,可以从我们自己的后端发送推送通知。所有主要浏览器都支持相同的功能。

Check this codelabfrom Google to better understand the implementation.

检查来自 Google 的此代码实验室以更好地了解实现。

Some Tutorials:

一些教程:

  • Implementing push notification in Django Here.
  • Using flask to send push notification Here& Here.
  • Sending push notifcaiton from Nodejs Here
  • Sending push notification using php Here& Here
  • Sending push notification from Wordpress. Here& Here
  • Sending push notification from Drupal. Here

Implementing own backend in various programming languages.:

用各种编程语言实现自己的后端。:

Further Readings:- - Documentation from Firefox website can be read here. - A very good overview of Web Push by Google can be found here.- An FAQ answeringmost common confusions and questions.

进一步阅读:- - 可以在此处阅读来自 Firefox 网站的文档。- 可以在此处找到对 Google Web Push 的非常好的概述- 回答最常见的困惑和问题的常见问题解答。

Are there any free services to do the same?There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:

是否有任何免费服务可以做同样的事情?有一些公司以免费、免费增值和付费模式提供类似的解决方案。我在下面列出了几个:

  1. https://onesignal.com/(Free | Support all platforms)
  2. https://firebase.google.com/products/cloud-messaging/(Free)
  3. https://clevertap.com/(Has free plan)
  4. https://goroost.com/
  1. https://onesignal.com/(免费 | 支持所有平台)
  2. https://firebase.google.com/products/cloud-messaging/(免费)
  3. https://clevertap.com/(有免费计划)
  4. https://goroost.com/

Note:When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.

注意:选择免费服务时,请记住阅读 TOS。免费服务通常通过为包括分析在内的各种目的收集用户数据来发挥作用。

Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org

除此之外,您需要使用 HTTPS 来发送推送通知。但是,您可以通过letsencrypt.org免费获取https

回答by greg.arnott

Javier covered Notifications and current limitations.

Javier 涵盖了通知和当前限制。

My suggestion: window.postMessagewhile we wait for the handicapped browser to catch up, else Worker.postMessage()to still be operating with Web Workers.

我的建议:window.postMessage当我们等待残障浏览器赶上时,否则Worker.postMessage()仍然使用 Web Workers。

These can be the fallback option with dialog box message display handler, for when a Notification feature test fails or permission is denied.

这些可以是带有对话框消息显示处理程序的回退选项,用于当通知功能测试失败或权限被拒绝时。

Notification has-feature and denied-permission check:

通知具有功能和拒绝权限检查:

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

回答by djfdev

You can push data from the server to the browser via Server Side Events. This is essentially a unidirectional stream that a client can "subscribe" to from a browser. From here, you could just create new Notificationobjects as SSEs stream into the browser:

您可以通过Server Side Events将数据从服务器推送到浏览器。这本质上是一个单向流,客户端可以从浏览器“订阅”。从这里开始,您可以在NotificationSSE 流入浏览器时创建新对象:

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

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

A bit old, but this article by Eric Bidelmanexplains the basics of SSE and provides some server code examples as well.

有点旧,但Eric Bidelman 的这篇文章解释了 SSE 的基础知识,并提供了一些服务器代码示例。

回答by Javier Conde

GCM/APNS are only for Chrome and Safari respectively.

GCM/APNS 分别仅适用于 Chrome 和 Safari。

I think you may be looking for Notification:

我想你可能正在寻找Notification

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

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

It works in Chrome, Firefox, Opera and Safari.

它适用于 Chrome、Firefox、Opera 和 Safari

回答by collimarco

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

我假设您在谈论真正的推送通知,即使用户没有浏览您的网站(否则请查看 WebSockets 或长轮询等遗留方法)。

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

我们可以使用 GCM/APNS 向包括 Firefox 和 Safari 在内的所有 Web 浏览器发送推送通知吗?

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

GCM 仅适用于 Chrome,APNs 仅适用于 Safari。每个浏览器制造商都提供自己的服务。

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

如果不是通过 GCM,我们可以有自己的后端来做同样的事情吗?

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).

Push API 需要两个后端!一种由浏览器制造商提供,负责向设备发送通知。另一个应该是你的(或者你可以使用像Pushpad这样的第三方服务),负责触发通知并联系浏览器制造商的服务(即 GCM、APNs、Mozilla 推送服务器)。

Disclosure: I am the Pushpad founder

披露:我是 Pushpad 创始人

回答by abderrahime sanadi

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

这是对所有浏览器进行推送通知的简单方法https://pushjs.org

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

回答by TRiNE

May I redefine you question as below

我可以重新定义你的问题如下

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

我们可以拥有自己的后端来向 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 APIprotocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

是的。到今天(2017/05),您可以使用相同的客户端和服务器端实现来处理 Chrome、Firefox 和 Opera(没有 Safari)。因为他们以相同的方式实现了网络推送通知。那是W3C 的Push API协议。但是 Safari 有自己的旧架构。所以我们要单独维护Safari。

Refer browser-pushrepo 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.

请参阅browser-pushrepo 获取指南,以使用您自己的后端为您的 web 应用程序实现 web 推送通知。它通过示例解释了如何在没有任何第三方服务的情况下为 Web 应用程序添加 Web 推送通知支持。

回答by Arjun singh

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

截至目前,GCM 仅适用于 chrome 和 android。同样,firefox 和其他浏览器也有自己的 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.
  1. 您需要客户端脚本代码,即服务工作者,请参阅(谷歌推送通知)。虽然这对于其他浏览器来说保持不变。

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

2.使用Ajax获取端点后,将其与浏览器名称一起保存。

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.您需要根据您的要求创建具有标题、消息、图标、点击 URL 字段的后端。现在点击发送通知后,调用一个函数说send_push()。例如,在此为不同浏览器编写代码

3.1. for chrome

3.1. 镀铬

 $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

3.2. 对于 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...

其他浏览器请谷歌...

回答by ColacX

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

我建议使用pubnub。然而,我尝试从浏览器使用 ServiceWorkers 和 PushNotification,但是当我尝试时,webviews 不支持这一点。

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

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