浏览器推送通知只需轮询网络服务器

Posted

技术标签:

【中文标题】浏览器推送通知只需轮询网络服务器【英文标题】:Browser push notification by simply polling webserver 【发布时间】:2016-04-28 19:33:07 【问题描述】:

即使页面未打开,我也需要创建浏览器推送消息。但我有一些限制,因为我在 Salesforce 中开发它。因此,当页面加载时,我有调用后端方法并在回调函数中获得响应的 javascript 块。而且我发现理论上我可以使用 serviceWorker,它可以通过 postMessages 与页面通信,它可以显示通知。我已经找到了一个通过单击按钮显示通知的示例,但我仍然需要找到使用 serviceWorker 与页面通信以从服务器获取响应的方法。 我已经看过这个关于 serviceWorker http://www.html5rocks.com/en/tutorials/service-worker/introduction/ 的指南,但对我来说不是很清楚。我不想使用任何中间件作为 GCM,只在客户端使用 JS。 请给我一些示例代码。

【问题讨论】:

你能澄清你的目标吗?如果您只想在页面打开时显示通知,则不需要服务人员。 @Marco 我需要在页面关闭时收到通知。这是示例storage-cdn.realtime.co/chrome-push/index.html 很遗憾,如果不使用浏览器的推送服务,页面关闭时无法收到通知。 【参考方案1】:

不...目前只有一种方法可以在您的网站关闭时使用 service worker api 向用户显示推送通知。

只有在您的网站正常运行时,第一种方式才会向您显示推送通知。 1)Ajax 轮询 这种方法被称为 Facebook 使用的彗星方法。在这种方法中,您将定期轮询服务器(意味着您需要定期对服务器进行 ajax 调用)以检查用户是否有任何新的通知要显示。请检查以下代码 $(文档).ready(函数 () setInterval(updateCount, 120000); ); var updateCount = 函数() var url = example.com // 给你自己的 url

    $.ajax(

        url:ajaxURl,
        type: "POST",
        dataType:"json",
        error: function(error)
                console.log("Error occured in the ajax call while saving the endpoint",error);
             ,
        success:function(data)
          console.log(data)
          if(data == new notifcation)
          //then show notification 
          
        ,
        timeout:60000
    );

;

This is simple approach to show the notification to the  user. 
Cons:- 1)It will trigger to many ajax call to the server which will eventually increase the load on the server.
        2)User have to be logged in to the system then only you can show notification to end user.

2) 服务工作者 API 在这种方法中,您需要在客户端浏览器中注册 service worker api。一旦服务器工作者 api 被注册,它将在浏览器的后台运行并等待推送事件。 当推送事件触发时,即使您的用户没有登录到您的网站,Service Worker api 也会触发推送通知。

Cons:- 1)the service worker api will only run in the certain browser 
       2)Your website should https for using the service worker api as they already mention in the article.

我希望我回答了你的问题..

【讨论】:

你提到的第一种方法是完全错误的!! @ravi-gupta 仔细阅读问题“当页面未打开时”

以上是关于浏览器推送通知只需轮询网络服务器的主要内容,如果未能解决你的问题,请参考以下文章

如何创建从服务器到所有通知授予用户的网络推送通知?

在 Blackberry(服务器端)中为 PhoneGap App 推送通知

网络推送 201 但在设备上看不到通知

有没有办法从 Google appengine 标准向网络浏览器发送推送通知? [关闭]

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

Web Notification 可以像推送通知服务一样工作吗?