推送消息 web push notification

参考 : 

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);
}

 

转载于:https://www.cnblogs.com/keatkeat/p/7503615.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值