借助原生应用安装提示,您可以让用户快速、 直接从应用商店将您的原生应用无缝安装到其设备上, 而无需离开浏览器,也不会显示令人厌烦的插页。
条件是什么?
如需向用户显示原生应用安装提示,您的网站必须满足以下条件:
- 既不是 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
属性会告知浏览器向用户显示原生应用,而不是 Web 应用。如果您未设置此值或将其设为 false
,浏览器将改为提示用户安装 Web 应用。
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
属性返回的 promise。通过
promise 会在提示符后返回包含 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 设备来缩小范围,以确定应用图标的网址。