原生應用程式安裝提示可以讓使用者快速 可以直接從應用程式商店將原生應用程式安裝到裝置上 而且不需要離開瀏覽器 也不需要顯示擾人的插頁式廣告
評選標準為何?
您的網站必須 必須符合下列條件:
- 不是網頁應用程式或裝置上目前安裝的原生應用程式。
- 包含以下內容的Web 應用程式資訊清單:
short_name
name
(用於橫幅提示)icons
,包括 192 像素和 512 像素的版本prefer_related_applications
為true
- 含有資訊的
related_applications
物件 關於這個應用程式
- 透過 HTTPS 提供
只要符合這些條件,系統就會觸發 beforeinstallprompt
事件。個人中心
可用來提示使用者安裝您的原生應用程式
必要的資訊清單屬性
如要提示使用者安裝原生應用程式,您需要新增兩項屬性
加入網頁應用程式資訊清單,prefer_related_applications
related_applications
。
"prefer_related_applications": true,
"related_applications": [
{
"platform": "play",
"id": "com.google.samples.apps.iosched"
}
]
prefer_related_applications
prefer_related_applications
屬性會指示瀏覽器向使用者顯示原生應用程式,而非網路應用程式。如果您未設定這個值,或設定為 false
,瀏覽器會提示使用者改為安裝網路應用程式。
related_applications
related_applications
是陣列,其中包含物件清單,可向瀏覽器指出您偏好的原生應用程式。每個物件都必須包含
platform
屬性和 id
屬性。platform
為 play
而 id
是您的 Play 商店應用程式 ID。
顯示安裝提示
如要顯示安裝對話方塊,您必須:
- 監聽
beforeinstallprompt
事件。 - 通知使用者,只要輕觸按鈕或其他可產生使用者手勢事件的元素,即可安裝原生應用程式。
- 在已儲存的
beforeinstallprompt
事件上呼叫prompt()
,即可顯示提示。
聆聽beforeinstallprompt
如果符合條件,Chrome 就會觸發 beforeinstallprompt
活動。您可以用這個方式指定可安裝的應用程式,然後提供提示
使用者進行安裝
觸發 beforeinstallprompt
事件後,儲存事件的參照。
並更新使用者介面,指出使用者可以安裝您的應用程式。
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
});
通知使用者可以安裝您的應用程式
如果想通知使用者安裝應用程式,最好的方法是新增按鈕 或其他元素加入使用者介面請勿顯示全頁插頁式廣告或其他可能令人厭煩或分心的元素。
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI notify the user they can add to home screen
btnAdd.style.display = 'block';
});
顯示提示
如要顯示安裝提示,請在使用者手勢中對已儲存的事件呼叫 prompt()
。系統會顯示強制回應對話方塊,詢問使用者
即可將你的應用程式加入他們的主畫面
接著,請聆聽 userChoice
屬性傳回的承諾。提示顯示並由使用者回應後,承諾會傳回具有 outcome
屬性的物件。
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
在延遲事件中,您只能呼叫 prompt()
一次。如果使用者關閉
則您需要等到 beforeinstallprompt
事件觸發
就可以前往下一頁
使用內容安全政策時的特別注意事項
如果您的網站採用限制性的內容安全性政策,請務必將 *.googleusercontent.com
新增至 img-src
指令,讓 Chrome 從 Play 商店下載與應用程式相關聯的圖示。
在某些情況下,*.googleusercontent.com
可能會比預期的冗長。您可以透過遠端偵錯 Android 裝置,判斷應用程式圖示的網址,以便縮小範圍。