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

我正在尝试了解我们是否可以使用桌面通知实现浏览器推送通知,我相信这是Web通知API所做的。我看到了一个谷歌文档关于如何为Chrome在这里和这里。

现在我还不明白的是:

我们是否可以使用GCM/APNS向包括Firefox和Safari在内的所有Web浏览器发送推送通知? 如果不通过GCM,我们可以有自己的后端来做同样的事情吗?

我相信所有这些答案都可以帮助很多有类似困惑的人。


当前回答

这里有一个完整的html工作示例。 只需要替换图像,文本,就可以了!

<html lang="en">
  <head>
    <meta charset="utf-8" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="script.js"></script>
    <link rel="icon" href="favicon.ico" type="image/png">
    <title>Push</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  
  </head>

  <body>
    <div class="centrado">

    


<div class="card text-center shadow">
  <div class="card-header">
    Push Notifications 
  </div>
  <div class="card-body">
    <h5 class="card-title">Test for Push Notifications</h5>
    <p class="card-text">Click twice, first for the permission</p>
    <button class="btn btn-danger" id="btn-show-notification">Notify</button>
  </div>
  <div class="card-footer text-muted">
    aledc7
  </div>
</div>

</div>


  </body>



<script>
  $(document).ready(function () {
  $(document).on('DOMContentLoaded', function () {
    // Request desktop notifications permission on page load

    if (!Notification) {
      console.log('Notification is not compatible');
      return;
    }

    if (Notification.permission !== 'granted') {
      Notification.requestPermission();
    }
  });

  function showNotification() {
    if (Notification.permission !== 'granted') {
      Notification.requestPermission();
    } else {
      const options = {
        body: 'Your text for the Notification,
        dir: 'ltr',
        image: 'your_image.png' //must be 728x360px
      };
      const notification = new Notification('Title Notification', options);

      notification.onclick = function () {
        window.open('https://stackoverflow.com/users/10220740/ale-dc');
      };
    }
  }

  $('#btn-show-notification').on('click', showNotification);
});
</script>


<style>
  .centrado{
    /* Centrado Horizontal */
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    vertical-align: middle;

    /* Centrado Vertical */
    margin: 0;
    position: absolute;
    top: 50%;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);


}

.shadow{
  filter: drop-shadow(2px 4px 8px #585858);
}


</style>

</html>

其他回答

您可以通过服务器端事件将数据从服务器推送到浏览器。这本质上是一个单向流,客户端可以从浏览器“订阅”到它。从这里,你可以创建新的通知对象,作为se流到浏览器:

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

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

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

Javier介绍了通知和当前的限制。

我的建议是:窗户。当我们等待缺陷浏览器赶上时,Worker.postMessage()仍在使用Web Workers操作。

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

通知has-feature和denied-permission检查:

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

这是一个简单的方法做推送通知所有浏览器https://pushjs.org

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

我建议使用pubnub。我尝试使用ServiceWorkers和推送通知从浏览器,然而,当我尝试它的webview不支持这一点。

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

到目前为止,GCM只适用于chrome和android。 同样,firefox和其他浏览器也有自己的api。

现在的问题是,如何实现推送通知,使其适用于所有具有自己后端的常见浏览器。

你需要客户端脚本代码,即service worker,参考(谷歌推送通知)。尽管这对其他浏览器来说是一样的。

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

3.您需要创建后端,其中有字段的标题,消息,图标,点击URL根据您的需求。现在,在单击发送通知之后,调用函数send_push()。例如,在这里为不同的浏览器编写代码

3.1. 在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. 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);

其他浏览器请谷歌…