简易流程 Server --(Push)--> Google Server --(Notification)--> User Device

简易重点
* 注册页面需为HTTPS 协定,可使用locathost,不可在无痕模式执行
* PUSH 至 Google Server 时,没法传递Payload


实作
1. 申请Google帐号,开通API权限,取得 API_KEY & PROJECT_NUMBER
https://console.developers.google.com/

2. 注册页面 增加 manifest 参照


"optional_permissions": ["notifications"], // 页面需要的权限
"gcm_sender_id": ""

3. 注册页面 增加 javascript
注册sw.js ,使其成为Chrome 背景执行程式    

<script>
if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('sw.js').then(function(reg) { 
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function(sub) {
console.log('endpoint:', sub.endpoint); <--- 取得endpoint (官方叫 Subscription ID) 后续使用
});
}).catch(function(error) {
console.log(':^(', error);
});
}
</script>


4. PUSH 至 GOOGLE

#curl --header 
"Authorization: key=" 
--header "Content-Type: application/json" 
https://android.googleapis.com/gcm/send 
-d "{\"registration_ids\":[\"\"]}"  <--- Array 里面放入上一步骤取得的endpoint , 上限为1000则


5. 接收GOOGLE 的 Notification 并显示,在Sw.js中

<script>
self.addEventListener('push', function(event) { 
var title = 'Push message';
event.waitUntil(
self.registration.showNotification(title, {
body: 'The Message',
icon: 'images/icon.png',
tag: 'my-tag'
}));
});
</script>    


可参考
https://developers.google.com/web/fundamentals/getting-started/push-notifications/step-04?hl=en

查看原文 >>
相关文章