# 用 Vue 做 PWA 推播功能 - 目的:設計一支 API,打下去後手機通知要跳出來。 - Code: https://github.com/johnson86tw/pwa-notification - 測試機器:iphone SE 2 :::info 以下所指稱之 PWA (progressive web app) 是指在手機上,將網頁「加入主畫面」後,從主畫面上的 app 點進去後打開的那個。 ::: ## 步驟 1. 瞭解如何 register sw.ts,了解 sw 的 lifecycle 和訂閱事件的方法 2. 使用 Notification API 開啟通知、跳出通知。 3. 使用 Push API 訂閱後端 api,使用 sw push 事件接受後端的 web push。 4. 實作 desktop chrome:設計一支 server api,打下去後,已訂閱的通知必須顯示出來。 - 關閉網頁,打 server api 也能出現通知。 - 關閉 chrome 瀏覽器,打 server api 也能出現通知。 5. 實作 PWA: 能夠在手機上跳出通知 - 必須使用 https 才能開通 request permission。(使用 chrome 的「加入主畫面」 是可行的,不一定要用 safari。) - PWA 的通知設定能夠在 iphone 的「設定 > 通知」裡面進行調整。 ## 推薦教材:Push Notifications with Service worker Part 1 https://www.youtube.com/watch?v=oDIYl3G613E - Application > Service workers > See all registrations 可以看到超多網域在你的 chrome 瀏覽器上登記 service worker - chrome desktop 可以觸發通知,記得在 settings 的地方要將 chrome 通知打開 - chrome mobile 是不支援 Notification API 的,除非把網站加入主畫面,但目前情況是,web app 上 request permission 被拒絕,尚找不出原因。 Part 2 https://www.youtube.com/watch?v=3bvWX7bgwV8&t=1s - Push service: Push service 是連接 client 和 server 之間的服務,Chrome 需要 application server key,它是一個公私鑰對,Firefox 則可以不用。 Part 3 https://www.youtube.com/watch?v=5gls_e1JyeY&t=129s - The [Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) gives web applications the ability to receive messages pushed to them from a server - 產生 vapid keys 公私鑰對,公鑰放在 client,私鑰放在 backend ``` npx web-push generate-vapid-keys ``` - backend 需要安裝 ``` pnpm install web-push ``` ## 參考專案 - [elk - service-worker](https://github.com/elk-zone/elk/tree/main/service-worker) - [yt-playlist-notifier](https://github.com/jeffposnick/yt-playlist-notifier) ## Q&A ### 本地前端網頁在手機上無法呼叫後端 API - PWA 下,前端使用 https 才能啟用通知功能,可以使用 ngrok。 - 但是 backend 不是 https,因此就算使用 local network ip 也會被 browser 擋掉 - ngrok 免費版一次只能 host 一個 https 端口 - 解法:使用 nginx 反向代理 frontend 和 backend,再使用 ngrok 對上 nginx 的 port - `new Notification('showNotification')` 在 desktop chrome 有反應,在 pwa 沒有作用,要使用 sw 的 `registration.showNotification`,才能在手機上出現通知。 ## Reference - [如何透過PWA 的 PUSH API,讓手機推播通知?](https://medium.com/@gxgemini777/%E8%A6%81%E7%94%A8pwa%E5%AF%A6%E7%8F%BE%E8%83%8C%E6%99%AF%E7%9A%84%E9%80%9A%E7%9F%A5%E6%8E%A8%E6%92%AD-%E5%8D%B3-%E5%9C%A8%E4%BD%BF%E7%94%A8%E8%80%85%E6%9C%AA%E9%96%8B%E5%95%9F%E6%88%91%E5%80%91%E7%9A%84pwa%E6%87%89%E7%94%A8%E7%A8%8B%E5%BC%8F%E7%9A%84%E7%8B%80%E6%B3%81%E4%B8%8B-%E4%B9%9F%E5%90%8C%E6%A8%A3%E5%8F%AF%E4%BB%A5%E9%80%8F%E9%81%8E%E6%89%8B%E6%A9%9F%E7%9A%84%E9%80%9A%E7%9F%A5%E7%B3%BB%E7%B5%B1%E9%80%B2%E8%A1%8C%E6%B6%88%E6%81%AF%E7%9A%84%E6%8E%A8%E9%80%81-%E6%B6%89%E5%8F%8A%E5%85%A9%E5%80%8B%E4%B8%BB%E8%A6%81%E7%9A%84%E6%8E%A5%E5%8F%A3-notifications-api-%E5%92%8C-push-716e9da31562) - [Vite PWA - Server push notifications](https://vite-pwa-org.netlify.app/workbox/inject-manifest.html#server-push-notifications) - [理解 Web Push Notification](https://hackmd.io/@wtflink515/HyjOvWtO_)