前言
Progressive Web Application (PWA) 可以讓使用者連到該網站後,進行安裝。
要有什麼條件才可以讓你的 PWA 程式是可以被安裝的呢?
實作
html head 設定
在 html 的 head 中要設定 manifest、apple-touch-icon 等資訊,如下,
1 | <link rel="manifest" href="manifest.json"> |
serviceWorker
serviceWorker js file 中要監聽 fetch event,
1 | self.addEventListener('fetch', () => { |
manifest.json
簡單的 manifest.json 設定如下
1 | { |
當然,icons 所在的圖檔也是必需存在的哦。
開啟 Chrome 的開發者工具,點選 Application ,再點左上方的 Manifest 。
如果看到沒有任何錯誤會警告,就表示這個 Web App 可以被安裝,如下圖,

透過 Browser 安裝的方式
而透過 Browser 的安裝方式有 4 種。
1.在 Browser 網址列上按上 +圈 ,如上面的圖。
2.手機透過 Browser 會顯示安裝的畫面

3.在 Browser 右上方 按下點點點後,選擇 安裝「你的AP」…

4.畫面上的 Button ,按下後,顯示 安裝「你的AP」…

要如何讓使用者按下Button後,出現安裝 App 呢?
1.在畫面上建立 Button
1 | <button id="btnInstall" class="btn btn-success">Install App</button> |
2.監聽 beforeinstallprompt ,並將 event 物件存下來
1 | let installPromptEvent; |
3.Button click 事件時,呼叫 beforeinstallprompt event 的 prompt method
1 | const installAppButton = document.getElementById("btnInstall"); |
註:beforeinstallprompt event 只在 Chromium-based browser 有效