close

簡易流程 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

arrow
arrow
    文章標籤
    GCM Notification
    全站熱搜

    samage 發表在 痞客邦 留言(0) 人氣()