使用者可能不熟悉 PWA 安裝程序。開發人員可以判斷邀請使用者安裝應用程式的適當時機,並改善預設的瀏覽器安裝提示。讓我們看看有哪些工具。
改善安裝對話方塊
如果 PWA 符合安裝條件,瀏覽器會提供預設安裝提示。瀏覽器會使用網頁應用程式資訊清單中的 name
和 icons
屬性建構提示。
部分瀏覽器會使用資訊清單中的宣傳欄位 (包括 description
、categories
和 screenshots
),提升安裝提示體驗。舉例來說,在 Android 裝置上使用 Chrome 時,如果 PWA 提供 description
和 screenshots
欄位的值,安裝對話方塊體驗就會從小型「新增至主畫面」資訊列,變成較大且更詳細的對話方塊,類似於應用程式商店的安裝提示。
beforeinstallprompt 事件
瀏覽器的安裝提示是讓使用者安裝 PWA 的第一步。如要實作自己的安裝體驗,應用程式仍須通過安裝條件:瀏覽器偵測到應用程式可安裝時,會觸發 beforeinstallprompt
事件。您需要實作這個事件處理常式,才能自訂使用者體驗。步驟如下:
- 監聽
beforeinstallprompt
事件。 - 請儲存這項資訊,稍後會用到。
- 從 UI 觸發。
請參閱下列程式碼,瞭解 beforeinstallprompt
事件的事件監聽器範例,以及如何擷取並自訂使用。
// This variable will save the event for later use.
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevents the default mini-infobar or install dialog from appearing on mobile
e.preventDefault();
// Save the event because you'll need to trigger it later.
deferredPrompt = e;
// Show your customized install prompt for your PWA
// Your own UI doesn't have to be a single element, you
// can have buttons in different locations, or wait to prompt
// as part of a critical journey.
showInAppInstallPromotion();
});
接著,如果使用者點選自訂安裝按鈕,請使用先前儲存的 deferredPrompt
並呼叫其 prompt()
方法,因為使用者仍須透過瀏覽器程序安裝應用程式。您所做的只是延遲事件,直到提供適當的背景資訊,鼓勵使用者安裝 PWA 為止。
擷取事件後,您就能為使用者新增提示和誘因,鼓勵他們安裝應用程式,並在使用者參與度較高時提示安裝。
在下列情況下,系統不會觸發事件:
- 使用者已安裝目前的 PWA (僅適用於 Android 上的電腦和 WebAPK)。
- 應用程式未通過 PWA 安裝條件。
- PWA 無法在目前裝置上安裝,原因不明 (例如裝置處於 Kiosk 模式或沒有權限)。
最適合輸入提示的位置
提示顯示位置取決於應用程式,以及使用者最常與內容和服務互動的時間。擷取 beforeinstallprompt
時,您可以引導使用者瞭解繼續使用應用程式的原因,以及安裝應用程式的好處。您可以在應用程式的任何位置顯示安裝提示。常見模式包括:側邊選單、完成訂單等重要使用者歷程後,或註冊頁面後。詳情請參閱「宣傳 PWA 安裝的模式」。
收集數據分析資料
使用數據分析有助於瞭解在何處和何時顯示提示。您可以使用 beforeinstallprompt
事件中的 userChoice
屬性;userChoice
是會以使用者採取的動作解析的 Promise。
// Gather the data from your custom install UI event listener
installButton.addEventListener('click', async () => {
// deferredPrompt is a global variable we've been using in the sample to capture the `beforeinstallevent`
deferredPrompt.prompt();
// Find out whether the user confirmed the installation or not
const { outcome } = await deferredPrompt.userChoice;
// The deferredPrompt can only be used once.
deferredPrompt = null;
// Act on the user's choice
if (outcome === 'accepted') {
console.log('User accepted the install prompt.');
} else if (outcome === 'dismissed') {
console.log('User dismissed the install prompt');
}
});
備用
如果瀏覽器不支援 beforeinstallprompt
或事件未觸發,就無法透過其他方式觸發瀏覽器的安裝提示。不過,在允許使用者手動安裝 PWA 的平台 (例如 iOS),您可以向使用者顯示這些操作說明。
您應只在瀏覽器模式中顯示這些指示;其他顯示選項 (例如 standalone
或 fullscreen
) 表示使用者已安裝應用程式。
如要只在瀏覽器模式中算繪元素,請使用 display-mode
媒體查詢:
#installInstructions {
display: none
}
@media (display-mode: browser) {
#installInstructions {
display: block
}
}
程式碼實驗室
程式庫
如需協助顯示自訂安裝提示,請參閱下列程式庫: