設為可安裝

監聽 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. 將安裝事件記錄到 Analytics 或其他機制。

代碼:

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

延伸閱讀

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

你還可以採取下列行動: