更新 : 2019-06-29

如果要监听 notification action 可以使用 notificationclick

常用的方式是,点击后打开 windows

https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web

  1. self.addEventListener('notificationclick', function(event) {
  2. console.log('On notification click: ', event.notification.tag);
  3. // Android doesn't close the notification when you click on it
  4. // See: http://crbug.com/463146
  5. event.notification.close();
  6.  
  7. // This looks to see if the current is already open and
  8. // focuses if it is
  9. event.waitUntil(
  10. clients.matchAll({
  11. type: "window"
  12. })
  13. .then(function(clientList) {
  14. for (var i = 0; i < clientList.length; i++) {
  15. var client = clientList[i];
  16. if (client.url == '/' && 'focus' in client)
  17. return client.focus();
  18. }
  19. if (clients.openWindow) {
  20. return clients.openWindow('/');
  21. }
  22. })
  23. );
  24. });

如果没有打开就开,如果有 focus 就好了。

参考 :

https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/   ( step by step 教程 )

https://github.com/gauntface/web-push-book/blob/master/src/demos/node-server/frontend/app.js#L33  ( 教程里的源码 )

https://web-push-codelab.glitch.me/ ( 制造 public/private key 的机器 )

https://github.com/web-push-libs/web-push-csharp  ( asp.net send to push service )

首先这个功能只有 chrome firefox 实现了.

IOS safari 是没有的 https://blog.izooto.com/ios-push-notifications-safari/

step by step 的依据这个做就可以了

https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/

push notification 的原理和过程大致是这样

会使用到 html5  service work 和 push API

首先开启 service work 然后要求 push 的 permission

之后会得到一个授权资料, 把资料存入 database 里, 当想推送的时候把信息和授权资料 send to 一个第三方机构 (push service)

不同游览器会是不同的机构. 之后机构就会把我们的信息给发出去了.

例子 :

  1. export class AppComponent implements OnInit {
  2.  
  3. constructor(
  4.  
  5. ) { }
  6.  
  7. private async registerWebWorkerAsync() {
  8. return navigator.serviceWorker.register('/assets/sw.js', { scope: '/assets/' });
  9. }
  10.  
  11. private async askPermissionAsync() {
  12. // callback 和 promise 都实现, 视乎有些游览器只有 callback 接口.
  13. return new Promise((resolve, reject) => {
  14. let permissionResult = Notification.requestPermission((result) => {
  15. resolve(result);
  16. });
  17. if (permissionResult) {
  18. permissionResult.then(resolve, reject);
  19. }
  20. })
  21. .then((permissionResult) => {
  22. if (permissionResult !== 'granted') {
  23. throw new Error('We weren\'t granted permission.');
  24. }
  25. });
  26. }
  27.  
  28. private urlBase64ToUint8Array(base64String: string) {
  29. let padding = '='.repeat((4 - base64String.length % 4) % 4);
  30. let base64 = (base64String + padding)
  31. .replace(/\-/g, '+')
  32. .replace(/_/g, '/');
  33.  
  34. let rawData = window.atob(base64);
  35. let outputArray = new Uint8Array(rawData.length);
  36.  
  37. for (let i = 0; i < rawData.length; ++i) {
  38. outputArray[i] = rawData.charCodeAt(i);
  39. }
  40. return outputArray;
  41. }
  42.  
  43. async click() {
  44. let registration = await this.registerWebWorkerAsync();
  45.  
  46. await this.askPermissionAsync();
  47.  
  48. let subscribeOptions = {
  49. userVisibleOnly: true,
  50. applicationServerKey: this.urlBase64ToUint8Array(
  51. // public key
  52. 'BIdckxOfE3LPlcn9xLfoOP5i0j9Ryrs4R0b2ieKZHELjoeGh_KFhw7fUm7IwRMPWnEl_u1MDgfINYU99AtN4oks'
  53. )
  54. };
  55.  
  56. let pushSubscription = await registration.pushManager.subscribe(subscribeOptions);
  57. console.log(JSON.stringify(pushSubscription)); //send the json to database
  58. }
  59.  
  60. async ngOnInit() {
  61.  
  62. }
  63.  
  64. }

sw.js

  1. self.addEventListener('install', function (event) {
  2. console.log("install");
  3. });
  4.  
  5. self.addEventListener('activate', function (event) {
  6. console.log("activate");
  7. });
  8.  
  9. self.addEventListener('push', function (event) {
  10. if (event.data) {
  11. console.log('This push event has data: ', event.data.text());
  12. } else {
  13. console.log('This push event has no data.');
  14. }
  15. const promiseChain = self.registration.showNotification('Hello, World.');
  16.  
  17. event.waitUntil(promiseChain);
  18. });

asp.net

  1. // 刚的 json 资料里就有 pushEndpoint, p256dh, auth
  1. var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/f0Y2dNnu4OA:APA91bFE8hoMTobAkWy4OctQKsB31_cVDZTigsYK2R-KY4_YWd8siTey2adgmf_sUGOQCeOPzFe_hUWivQDY5xTJSwHqcWWypXjQ0WL6r-mG08kbj7btmjV-SJV7mN_9wYpLmeyEncre";
  2. var p256dh = @"BPQmeaIyPVBmMq2Mh-wawz-wnSGgQkFeZf_BJQLs78He7PNm6Rt9q5w3RwTjcxR7qJNIrzawduK5ccUvS-9RYV0=";
  3. var auth = @"VHQbmWlrNju4kryCgcLqIg==";
  4.  
  5. var subject = @"mailto:hengkeat87@gmail.com";
  6. var publicKey = @"BIdckxOfE3LPlcn9xLfoOP5i0j9Ryrs4R0b2ieKZHELjoeGh_KFhw7fUm7IwRMPWnEl_u1MDgfINYU99AtN4oks";
  7. var privateKey = @"po1j4pj2opij43ij6daagp4i";
  8.  
  9. var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
  10. var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
  11. //var gcmAPIKey = @"[your key here]";
  12.  
  13. var webPushClient = new WebPushClient();
  14. try
  15. {
  16. await webPushClient.SendNotificationAsync(subscription, "payload", vapidDetails);
  17. //webPushClient.SendNotification(subscription, "payload", vapidDetails);
  18. //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
  19. }
  20. catch (WebPushException exception)
  21. {
  22. Console.WriteLine("Http STATUS code" + exception.StatusCode);
  23. }

推送消息 web push notification的更多相关文章

  1. iOS上简单推送通知(Push Notification)的实现

    iOS上简单推送通知(Push Notification)的实现 根据这篇很好的教程(http://www.raywenderlich.com/3443/apple-push-notification ...

  2. 苹果推送通知服务Push Notification探究总结(序)

    刚才发了两篇几个月前写的文档,觉得太敷衍了,想了想,还是来一发实在的. 再者,刚好上周研究了苹果的推送通知服务Push Notification,还是很有心得的,赶紧趁热打铁,记录一下,望与大家谈论下 ...

  3. iOS监听模式系列之推送消息通知

    推送通知 和本地通知不同,推送通知是由应用服务提供商发起的,通过苹果的APNs(Apple Push Notification Server)发送到应用客户端.下面是苹果官方关于推送通知的过程示意图: ...

  4. Android应用实现Push推送消息原理

            本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我 们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅 ...

  5. DWR实现后台推送消息到web页面

    DWR简介 DWR(Direct Web Remoting)可用于实现javascript直接调用java函数和后台直接调用页面javascript代码,后者可用作服务端推送消息到Web前端. (服务 ...

  6. Asp.net SignalR 实现服务端消息推送到Web端

              之前的文章介绍过Asp.net SignalR,  ASP .NET SignalR是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信.  今天我 ...

  7. Android push推送消息到达成功率优化

    Android push推送消息到达成功率优化 问题:server向client发送消息.未考虑client是否在线,这种消息到达率是非常低的. 第一次优化:使用server离线缓存数据,推断假设cl ...

  8. 使用极光推送(www.jpush.cn)向安卓手机推送消息【服务端向客户端主送推送】C#语言

    在VisualStudio2010中新建网站JPushAndroid.添加引用json帮助类库Newtonsoft.Json.dll. 在web.config增加appkey和mastersecret ...

  9. python使用pyapns进行ios推送消息

    Pyapns 提供了通用的Apple Push Notification Service (APNS).该解决方案使用了开源的Twisted server,支持原生的Python和Ruby API. ...

随机推荐

  1. div容器中内容垂直居中

    #box{ width:200px; height:200px; line-height: 200px; vertical-align: middle; margin: 5px; background ...

  2. Mac下Homebrew的安装与使用

    Homebrew简介,安装与使用 简介 Homebrew 官方网站 Homebrew是一个包管理器,用于安装Apple没有预装但你需要的UNIX工具.(比如著名的wget). Homebrew会将软件 ...

  3. 零基础Python爬虫实现(爬取最新电影排行)

    提示:本学习来自Ehco前辈的文章, 经过实现得出的笔记. 目标网站 http://dianying.2345.com/top/ 网站结构 要爬的部分,在ul标签下(包括li标签), 大致来说迭代li ...

  4. 如何获取sdcard的总容量

    activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android& ...

  5. ODAC(V9.5.15) 学习笔记(四)TCustomDADataSet(2)

    2.连接相关 名称 类型 说明 Connection 指向一个数据库连接对象 Disconnected 设置为True将在数据库关闭后继续保持数据集的开启状态. 3. 数据获取 名称 类型 说明 Fe ...

  6. Python, pandas: how to sort dataframe by index// Merge two dataframes by index

    pd.concat([df1, df2], axis=1) df.sort_index(inplace=True) https://stackoverflow.com/questions/404680 ...

  7. 【做题】HDU6331 Walking Plan——矩阵&分块

    题意:给出一个有\(n\)个结点的有向图,边有边权.有\(q\)组询问,每次给出\(s,t,k\),问从\(s\)到\(t\)至少经过\(k\)条边的最短路. \(n \leq 50, \, q \l ...

  8. Kubernetes相关概念

    This page explains how Kubernetes objects are represented in the Kubernetes API, and how you can exp ...

  9. TensorFlow 安装以及python虚拟环境

    python虚拟环境 由于TensorFlow只支持某些版本的python解释器,如Python3.6.如果其他版本用户要使用TensorFlow就必须安装受支持的python版本.为了方便在不同项目 ...

  10. Mysql视图、触发器、事务、储存过程、函数

    一.视图 什么是视图 视图是有一张表或多张表的查询结果构成的一张虚拟表 为什么使用视图 当我们在使用多表查询时 我们的sql语句可能会非常的复杂,如果每次都编写一遍sql'的话无疑是一件麻烦的事情,这 ...