【问题标题】:How can I do push notifications in an HTML5 Web application?如何在 HTML5 Web 应用程序中推送通知?
【发布时间】:2015-12-06 17:24:25
【问题描述】:

我有一个网络应用程序。当用户在特定页面上时,我想使用 HTML 5 内置通知 API 从服务器推送通知。有可能吗?

【问题讨论】:

    标签: javascript html push-notification web-push push-api


    【解决方案1】:

    您现在可以在 Chrome 中使用来自W3C Push API 的Service Workers 和PushManager 使用Web 应用程序进行真正的推送通知。

    请参阅文章Push Notifications on the Open Web,了解您可以使用的分步操作方法和代码 sn-ps。这是那篇文章中的一张图表,它解释了它周围的 UI 是什么样的。

    还有一个implementation of the Push API has already landed in Firefox;它的目标是在 2015 年 11 月在 Firefox 42 中发布。微软也有 indicated that the Push API is also under consideration for implementation in Edge team。

    下面是一个简单的代码示例,借鉴自 MDN。

    this.onpush = function(event) {
      console.log(event.data);
    }
    
    navigator.serviceWorker.register('serviceworker.js').then(
        function(serviceWorkerRegistration) {
            serviceWorkerRegistration.pushManager.subscribe().then(
                function(pushSubscription) {
                    console.log(pushSubscription.subscriptionId);
                    console.log(pushSubscription.endpoint);
                }, function(error) {
                    console.log(error);
                }
            );
        }
    );
    

    【讨论】:

    • 客户端很简单。服务器端呢?这不是问题的核心吗?
    • 谷歌云消息传递 (firebase) 方法是仅适用于 chrome 还是适用于 firefox?
    • @Vetterjack 我相信只有 chrome 和 android
    • 这里的教程有关于如何处理服务器端的信息:html5rocks.com/en/tutorials/websockets/basics 它涉及使用一种可以同时处理大量打开连接的技术。
    • 您只显示了答案的一半。你忘了服务器端
    【解决方案2】:

    这取决于你想要达到的目标:

    • 如果您想在浏览您的网站时向用户显示推送通知,您可以使用Web Notifications API,为通知提供“原生”样式;您还可以使用 SSE 或 WebSockets 等技术将通知从您的服务器推送到客户端
    • 如果您想要异地推送通知(即使用户不在您的网站上也会发送),您应该结合使用 Service Worker 和 Push API 来触发离线事件并使用用于显示通知的 Notifications API(请参阅 my answer)

    【讨论】:

      猜你喜欢
      • 2022-12-21
      • 1970-01-01
      • 2014-05-19
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多