使用者可能不熟悉 PWA 的安裝程序。身為開發人員,您將瞭解何時是邀請使用者安裝應用程式的適當時機。您也可以強化預設的瀏覽器安裝提示。我們來看看可用的工具。
改善安裝對話方塊
PWA 通過安裝條件時,瀏覽器就會提供預設安裝提示。瀏覽器會使用網頁應用程式資訊清單中的 name
和 icons
屬性建立提示。
部分瀏覽器可以使用資訊清單中的宣傳欄位 (包括 description
、categories
和 screenshots
) 改善安裝提示體驗。舉例來說,如果您的 PWA 提供 description
和 screenshots
欄位的值,當 PWA 提供 description
和 screenshots
欄位的值時,安裝對話方塊體驗會從小型「新增至主畫面」資訊列轉換成更詳細且詳盡的對話方塊,類似應用程式商店的安裝提示。
查看促銷活動欄位的實際運作情形:
beforeinstallprompt 事件
瀏覽器的安裝提示是讓使用者安裝 PWA 的第一步,如要導入自己的安裝體驗,應用程式仍須通過安裝條件:當瀏覽器偵測到應用程式可安裝時,就會觸發 beforeinstallprompt
事件。您必須實作這個事件處理常式才能自訂使用者體驗。做法如下:
- 監聽
beforeinstallprompt
事件。 - 請儲存起來 (稍後使用)。
- 從使用者介面觸發。
請參閱以下程式碼,瞭解 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。
提示推薦平台
看到提示的位置取決於您的應用程式,以及使用者最常與您的內容和服務互動的時機。擷取 beforeinstallprompt
後,您可以引導使用者瞭解繼續使用應用程式的原因,以及安裝應用程式可帶來的好處。
您可以選擇在應用程式的任何位置顯示安裝提示。常見模式包括:側邊選單、關鍵使用者操作 (例如完成訂單後) 或註冊頁面之後。詳情請參閱「宣傳 PWA 安裝的模式」。
收集數據分析
使用數據分析可協助您進一步瞭解要在哪些位置和時機呈現提示。您可以使用 beforeinstallprompt
事件中的 userChoice
屬性;userChoice
可保證會解決使用者執行的動作。
// 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');
}
});
實例觀摩
請嘗試在 Chromium 瀏覽器 (電腦版或 Android) 中實際操作以下範例。
備用
如果瀏覽器不支援 beforeinstallprompt
,或是事件未觸發,代表沒有其他方法可以觸發瀏覽器的安裝提示。但是,在允許使用者手動安裝 PWA 的平台上 (例如 iOS),您可以向使用者顯示這些操作說明。
這些操作說明只能在瀏覽器模式中算繪,其他顯示選項 (例如 standalone
或 fullscreen
) 則表示使用者已安裝應用程式。
如果只想在瀏覽器模式下算繪元素,請使用 display-mode
媒體查詢:
#installInstructions {
display: none
}
@media (display-mode: browser) {
#installInstructions {
display: block
}
}
程式碼研究室
程式庫
請參閱下列程式庫,瞭解如何轉譯自訂安裝提示: