這個故障包含網頁資訊清單,其中包含將網頁應用程式可安裝的必填欄位。
也有預設隱藏的安裝按鈕。
監聽 beforeinstallprompt 事件
瀏覽器觸發 beforeinstallprompt
事件時,表示可以安裝網頁應用程式,並顯示安裝按鈕。當應用程式符合安裝性條件時,就會觸發 beforeinstallprompt
事件。
擷取事件可讓開發人員自訂安裝,並在使用者認為是最佳時機時提示使用者進行安裝。
- 按一下「Remix to Edit」,讓專案可供編輯。
- 將
beforeinstallprompt
事件處理常式新增至window
物件。 - 將
event
儲存為全域變數,我們稍後需要使用該變數來顯示提示。 - 取消隱藏安裝按鈕。
代碼:
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()
必須透過使用者手勢呼叫。
- 為安裝按鈕新增點擊事件處理常式。
- 對已儲存的
beforeinstallprompt
事件呼叫prompt()
。 - 記錄提示結果。
- 將已儲存的
beforeinstallprompt
事件設為空值。 - 隱藏安裝按鈕。
代碼:
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
事件,追蹤這些安裝方式。
- 將
appinstalled
事件處理常式新增至window
物件。 - 將安裝事件記錄至數據分析或其他機制。
代碼:
window.addEventListener('appinstalled', (event) => {
console.log('👍', 'appinstalled', event);
// Clear the deferredPrompt so it can be garbage collected
window.deferredPrompt = null;
});
延伸閱讀
恭喜,您的應用程式現在已可安裝!
您還可以進行下列操作: