如何在HTML5 Web应用程序中推送通知?

问题描述:

我有一个Web应用程序.当用户位于特定页面上时,我想使用HTML 5内置通知API从服务器发出推送通知.有可能吗?

I have a web application. I want to use the HTML 5 inbuilt notifications API to do push notifications from the server when the user is on a particular page. Is it possible?

您可以使用 PushManager 来自 W3C推送API .

请参阅文章推送通知在开放式网络上获取有关您可以使用的分步操作方法和代码段的信息.这是该文章中的图表,解释了其周围的UI.

See the article Push Notifications on the Open Web for a step-by-step how-to and code snippets you can use. Here’s a diagram from that article that explains what the UI around it looks like.

Push API的实现也已经在Firefox中实现;它计划于2015年11月在Firefox 42中发布.Microsoft已表明也在考虑在Edge团队中实施Push API .

An implementation of the Push API has already landed in Firefox too; it’s targeted for shipping in November 2015 in Firefox 42. And Microsoft has indicated that the Push API is also under consideration for implementation in Edge team as well.

下面是一个简单的代码示例,是从MDN借来的.

Below is a simple code example, borrowed from 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);
            }
        );
    }
);