getReason()} "; $deleteFlag = DB::table(SUBSCRIPTION_TABLE_NAME)->where('endpoint', $endpoint)->delete(); echo var_dump($delet。JavaScript轻应用PWA实践全过程( 三 )。" />

JavaScript轻应用PWA实践全过程( 三 )


"; } 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实践过程"/>

function pushSubmit() { $.ajax({ url : '/admin/push/push_mess', method : 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data : $('#pushForm').serialize(), dataType : 'JSON', error : function(e){ alert('error'); }, success : function(resp){ if(resp.errcode === 0){ $('#pushResultMsg').html(resp.data); } else { alert(resp.errmsg); } } });}只需使用上述HTML,即可以推送相关信息,并且加上其他配置,还可以设置有效时间,推送时间等 。
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); }});


推荐阅读