設為可安裝

監聽 beforeinstallprompt 事件

瀏覽器觸發 beforeinstallprompt 事件時,表示可以安裝網頁應用程式,並向使用者顯示安裝按鈕。當應用程式符合可安裝條件時,系統會觸發 beforeinstallprompt 事件。

擷取事件後,開發人員就能自訂安裝程序,並在認為最合適的時機提示使用者安裝。

  1. 按一下「重混即可編輯」,即可編輯專案。
  2. 在 window 物件中新增 beforeinstallprompt 事件處理常式。
  3. 將 event 儲存為全域變數,稍後顯示提示時會用到。
  4. 取消隱藏安裝按鈕。

代碼:

window.addEventListener('beforeinstallprompt', (event) => {
  // Prevent the mini-infobar from appearing on mobile.
  event.preventDefault();
  console.log('👍', 'beforeinstallprompt', event);
  // Stash the event so it can be triggered later.
  window.deferredPrompt = event;
  // Remove the 'hidden' class from the install button container.
  divInstall.classList.toggle('hidden', false);
});

處理安裝按鈕點擊

如要顯示安裝提示,請對儲存的 beforeinstallprompt 事件呼叫 prompt()。呼叫 prompt() 是在安裝按鈕點擊處理常式中完成,因為 prompt() 必須透過使用者手勢呼叫。

  1. 為安裝按鈕新增點擊事件處理常式。
  2. 在儲存的 beforeinstallprompt 事件上呼叫 prompt()。
  3. 記錄提示的結果。
  4. 將儲存的 beforeinstallprompt 事件設為空值。
  5. 隱藏安裝按鈕。

代碼:

butInstall.addEventListener('click', async () => {
  console.log('👍', 'butInstall-clicked');
  const promptEvent = window.deferredPrompt;
  if (!promptEvent) {
    // The deferred prompt isn't available.
    return;
  }
  // Show the install prompt.
  promptEvent.prompt();
  // Log the result
  const result = await promptEvent.userChoice;
  console.log('👍', 'userChoice', result);
  // Reset the deferred prompt variable, since
  // prompt() can only be called once.
  window.deferredPrompt = null;
  // Hide the install button.
  divInstall.classList.toggle('hidden', true);
});

追蹤安裝事件

透過安裝按鈕安裝網頁應用程式,只是使用者安裝應用程式的其中一種方式。此外,使用者也可以透過 Chrome 選單、迷你資訊列和網址列中的圖示安裝 PWA。您可以監聽 appinstalled 事件,追蹤所有安裝方式。

  1. 將 appinstalled 事件處理常式新增至 window 物件。
  2. 將安裝事件記錄到數據分析或其他機制。

代碼:

window.addEventListener('appinstalled', (event) => {
  console.log('👍', 'appinstalled', event);
  // Clear the deferredPrompt so it can be garbage collected
  window.deferredPrompt = null;
});

延伸閱讀

恭喜,您的應用程式現在可以安裝了!

您還可以採取下列行動: