設為可安裝

這項故障包含網路資訊清單,內含將網頁應用程式設為可安裝的必填欄位。

此外,它還有一個預設為隱藏的安裝按鈕,

監聽 beforeinstallprompt 事件

當瀏覽器觸發 beforeinstallprompt 事件時,表示 可以安裝網頁應用程式,並顯示安裝按鈕 以便傳達給使用者應用程式符合 beforeinstallprompt 安裝條件

擷取事件可讓開發人員自訂安裝作業並提示使用者 進行最佳化調整

  1. 按一下「Remix to Edit」即可編輯專案。
  2. beforeinstallprompt 事件處理常式新增至 window 物件。
  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 的選單、迷你資訊列 按下網址列中的圖示。你可以 監聽 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;
});

延伸閱讀

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

您還可以進行以下操作: