推送消息 web push notification
更新 : 2019-06-29
如果要监听 notification action 可以使用 notificationclick
常用的方式是,点击后打开 windows
https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: "window"
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow('/');
}
})
);
});
如果没有打开就开,如果有 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)
不同游览器会是不同的机构. 之后机构就会把我们的信息给发出去了.
例子 :
export class AppComponent implements OnInit {
constructor(
) { }
private async registerWebWorkerAsync() {
return navigator.serviceWorker.register('/assets/sw.js', { scope: '/assets/' });
}
private async askPermissionAsync() {
// callback 和 promise 都实现, 视乎有些游览器只有 callback 接口.
return new Promise((resolve, reject) => {
let permissionResult = Notification.requestPermission((result) => {
resolve(result);
});
if (permissionResult) {
permissionResult.then(resolve, reject);
}
})
.then((permissionResult) => {
if (permissionResult !== 'granted') {
throw new Error('We weren\'t granted permission.');
}
});
}
private urlBase64ToUint8Array(base64String: string) {
let padding = '='.repeat((4 - base64String.length % 4) % 4);
let base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
let rawData = window.atob(base64);
let outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
async click() {
let registration = await this.registerWebWorkerAsync();
await this.askPermissionAsync();
let subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: this.urlBase64ToUint8Array(
// public key
'BIdckxOfE3LPlcn9xLfoOP5i0j9Ryrs4R0b2ieKZHELjoeGh_KFhw7fUm7IwRMPWnEl_u1MDgfINYU99AtN4oks'
)
};
let pushSubscription = await registration.pushManager.subscribe(subscribeOptions);
console.log(JSON.stringify(pushSubscription)); //send the json to database
}
async ngOnInit() {
}
}
sw.js
self.addEventListener('install', function (event) {
console.log("install");
});
self.addEventListener('activate', function (event) {
console.log("activate");
});
self.addEventListener('push', function (event) {
if (event.data) {
console.log('This push event has data: ', event.data.text());
} else {
console.log('This push event has no data.');
}
const promiseChain = self.registration.showNotification('Hello, World.');
event.waitUntil(promiseChain);
});
asp.net
// 刚的 json 资料里就有 pushEndpoint, p256dh, auth
var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/f0Y2dNnu4OA:APA91bFE8hoMTobAkWy4OctQKsB31_cVDZTigsYK2R-KY4_YWd8siTey2adgmf_sUGOQCeOPzFe_hUWivQDY5xTJSwHqcWWypXjQ0WL6r-mG08kbj7btmjV-SJV7mN_9wYpLmeyEncre";
var p256dh = @"BPQmeaIyPVBmMq2Mh-wawz-wnSGgQkFeZf_BJQLs78He7PNm6Rt9q5w3RwTjcxR7qJNIrzawduK5ccUvS-9RYV0=";
var auth = @"VHQbmWlrNju4kryCgcLqIg=="; var subject = @"mailto:hengkeat87@gmail.com";
var publicKey = @"BIdckxOfE3LPlcn9xLfoOP5i0j9Ryrs4R0b2ieKZHELjoeGh_KFhw7fUm7IwRMPWnEl_u1MDgfINYU99AtN4oks";
var privateKey = @"po1j4pj2opij43ij6daagp4i"; var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
//var gcmAPIKey = @"[your key here]"; var webPushClient = new WebPushClient();
try
{
await webPushClient.SendNotificationAsync(subscription, "payload", vapidDetails);
//webPushClient.SendNotification(subscription, "payload", vapidDetails);
//webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
}
catch (WebPushException exception)
{
Console.WriteLine("Http STATUS code" + exception.StatusCode);
}
推送消息 web push notification的更多相关文章
- iOS上简单推送通知(Push Notification)的实现
iOS上简单推送通知(Push Notification)的实现 根据这篇很好的教程(http://www.raywenderlich.com/3443/apple-push-notification ...
- 苹果推送通知服务Push Notification探究总结(序)
刚才发了两篇几个月前写的文档,觉得太敷衍了,想了想,还是来一发实在的. 再者,刚好上周研究了苹果的推送通知服务Push Notification,还是很有心得的,赶紧趁热打铁,记录一下,望与大家谈论下 ...
- iOS监听模式系列之推送消息通知
推送通知 和本地通知不同,推送通知是由应用服务提供商发起的,通过苹果的APNs(Apple Push Notification Server)发送到应用客户端.下面是苹果官方关于推送通知的过程示意图: ...
- Android应用实现Push推送消息原理
本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我 们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅 ...
- DWR实现后台推送消息到web页面
DWR简介 DWR(Direct Web Remoting)可用于实现javascript直接调用java函数和后台直接调用页面javascript代码,后者可用作服务端推送消息到Web前端. (服务 ...
- Asp.net SignalR 实现服务端消息推送到Web端
之前的文章介绍过Asp.net SignalR, ASP .NET SignalR是一个ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时通信. 今天我 ...
- Android push推送消息到达成功率优化
Android push推送消息到达成功率优化 问题:server向client发送消息.未考虑client是否在线,这种消息到达率是非常低的. 第一次优化:使用server离线缓存数据,推断假设cl ...
- 使用极光推送(www.jpush.cn)向安卓手机推送消息【服务端向客户端主送推送】C#语言
在VisualStudio2010中新建网站JPushAndroid.添加引用json帮助类库Newtonsoft.Json.dll. 在web.config增加appkey和mastersecret ...
- python使用pyapns进行ios推送消息
Pyapns 提供了通用的Apple Push Notification Service (APNS).该解决方案使用了开源的Twisted server,支持原生的Python和Ruby API. ...
随机推荐
- ora-12705解决方法
最近使用instant sqlplus测试时,遇到ora-12705,一开始以为是少了配置,经查是,NLS_LANG设置问题,设置为"SIMPLIFIED CHINESE_CHINA.ZHS ...
- MySQL更改relay-bin名称导致同步停止的解决办法
今天在优化io的时候,移动了从库relay-bin的位置,并将hostname部分去掉了,启动后,从库slave状态如下: mysql> show slave status\G; ******* ...
- docker 实践
https://doc.yonyoucloud.com/doc/docker_practice/etcd/etcdctl.html 启动http restful API docker批量映射端口 怎么 ...
- oracle基础——内存管理、优化
内存图解: 自动管理:11g:AMM 10g:ASMM SGA(system global area):由所有服务进程和后台进程共享 PGA(program global area): 由每个服务 ...
- Django使用多数据库
有些项目可能涉及到使用多个数据库的情况,方法很简单. 1.在settings中设定DATABASE 比如要使用两个数据库: DATABASES = { 'default': { 'NAME': 'ap ...
- [HEOI2016/TJOI2016]树
[HEOI2016/TJOI2016]树 思路 做的时候也是糊里糊涂的 就是求最大值的线段树 错误 线段树写错了 #include <bits/stdc++.h> #define FOR( ...
- IDEA移动到另一电脑
idea当电脑迁移后,可以直接将已安装的idea目录进行迁移(要保证迁移前后项目目录绝对路径相同) 步骤: 1.将idea的安装目录复制到另一台电脑上 2.将IDEA相关的配置路径下的目录页复制到另一 ...
- hihoCoder week8 状态压缩·一
状态压缩 写了两个半小时 太菜了 题目链接 https://hihocoder.com/contest/hiho8/problem/1 #include <bits/stdc++.h> ...
- position relative top失效的问题,温习下常用两种的居中方式
因为body和html,默认高度是auto 所以相对于他们作为父元素设置position:relative的top值需要加上body,html{height:100%;} <!DOCTYPE h ...
- eclipse安装spring boot插件spring tool suite
进行spring cloud的学习,要安装spring boot 的spring -tool-suite插件,我在第一次安装时,由于操作不当,两天才完全安装好,真的是要命了,感觉自己蠢死!下面就自己踩 ...