"; } else { $pushResult = $pushResult . "[failed]- {$endpoint}: {$report->getReason()}
"; $deleteFlag = DB::table(SUBSCRIPTION_TABLE_NAME)->where('endpoint', $endpoint)->delete(); echo var_dump($deleteFlag); if ($deleteFlag) { $pushResult = $pushResult . " delete success !
"; } } } $resp = array( 'errcode' => 0, 'errmsg' => '', 'data' => $pushResult ); return response()->json($resp);}提交推送的信息页面:
<section class="mod-inner"> <form class="bsf-form" id="pushForm"> <h2>推送消息</h2> <div class="bsf-unit"> <label class="bsf-label" for="title">标题:</label> <input type="text" name="title" class="bsf-item" value=https://www.isolves.com/it/cxkf/yy/js/2019-08-08/"轻应用PWA实践过程"/>
Web Push 授权、发起订阅、提交订阅
if ('PushManager' in window) { if (Notification.permission !== 'granted') { // 请求授权 askPermission(); } // 发起订阅 navigator.serviceWorker.ready.then(function(reg) {subscribe(reg)});}// 授权消息推送function askPermission() { return new Promise(function (resolve, reject) { var permissionResult = Notification.requestPermission(function (result) { resolve(result); // 旧版本 }); if (permissionResult) { permissionResult.then(resolve, reject); // 新版本 } }).then(function (permissionResult) { if (permissionResult !== 'granted') { alert('只有允许显示通知,您才能收到更新提醒,提醒一个月只会出现两三次,您可以在设置处修改 。'); } }).catch(e => console.log(e));}// 将base64的applicationServerKey转换成UInt8Arrayfunction urlBase64ToUint8Array(base64String) { var padding = '='.repeat((4 - base64String.length % 4) % 4); var base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); var rawData = https://www.isolves.com/it/cxkf/yy/js/2019-08-08/window.atob(base64); var outputArray = new Uint8Array(rawData.length); for (var i = 0, max = rawData.length; i < max; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray;}function subscribe(serviceWorkerReg) { serviceWorkerReg.pushManager.subscribe({ // 2. 订阅 userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array('BGMKbiifiMDHo5ZiXxziLuOC7GZaPGdDBfwZp4eYGUxUKvY1VMjNff814+Oi4jAQXnY1LMNgYahiV8gAzKaK+gQ=') }).then(function (subscription) { // 3. 发送推送订阅对象到服务器,具体实现中发送请求到后端api sendEndpointInSubscription(subscription); console.log('subscribe success'); }).catch(function (e) { console.log(e); // 订阅请求失败 if (Notification.permission === 'denied') { } });}function sendEndpointInSubscription(subscription) { let endpoint = subscription.endpoint; let publicKey = subscription.getKey('p256dh'); publicKey = publicKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(publicKey))) : null; let authToken = subscription.getKey('auth'); authToken = authToken ? btoa(String.fromCharCode.apply(null, new Uint8Array(authToken))) : null; const contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0]; const reqData = { endpoint, publicKey, authToken, contentEncoding, } console.log(reqData); $.ajax({ url : '/admin/push/save_subscription', method : 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data : reqData, dataType : 'JSON', error : function(e){ }, success : function(resp){ console.log('send success'); } });}endpoint: 为客户端推荐的地址,推送服务端便是用这个找到客户端的 。
publicKey: 公钥
authToken: 加密方式,好处是推送服务器也无法解密这个信息
contentEncoding: 编码方式
Service Worker 监听push,发出通知
// 监听server有push的消息,通知用户self.addEventListener('push', function (event) { console.log('push', event); if (!(self.Notification && self.Notification.permission === 'granted')) { return; } if (event.data) { var promiseChain = Promise.resolve(event.data.json()).then(data => { console.log(data); // 使用setTimeout之后,可以实现点击跳转,否则chrome不行 setTimeout(function(){ self.registration.showNotification(data.title, { body: data.body, icon: data.icon, badge: data.badge, data: { href: data.href, } }); }, 10); }); event.waitUntil(promiseChain); }});
推荐阅读
- 8 个提高 JavaScript 性能的方法
- 教你用这十种茶帮你轻松消除各种不适
- 喝茶可以预防中风 让自己更年轻哦
- 如何在家轻松练瑜伽
- 对标苹果iPhoneSE:小米高管确认轻薄单手小屏新机
- 车联网:未来5G核心应用场景之一,产业链趋于成熟,附相关个股
- 韩式减肥茶 让你轻松瘦身
- 保持年轻的运动有哪些
- 茶叶在食品上的应用
- 详解Spring MVC 构建入门级 Web 应用程序