我已经用Android手机创建了一个移动友好的网站,并添加了一些元信息,这样它就应该固定在iOS和jQuery的主屏幕上,并且应该作为web应用程序启动(换句话说:在浏览器中,但没有浏览器导航元素)。
它适用于iOS,但不适用于安卓4.4.2。
我按照this教程创建了与安卓兼容的web应用程序:
尽管添加了教程中列出的所有元信息,Android确实显示了我的网站的“添加到主页”按钮,但它不会启动没有浏览器导航元素的网站,如教程中所述。
我做错了什么?
发布于 2018-12-19 05:29:08
guide指出,从Chrome68开始,预计应用程序开发人员会在他们的应用程序中添加一个按钮。并且它应该只有在满足PWA criteria的情况下才能工作。然后,您应该能够使用以下代码来获取应用程序的回调,您可以向用户显示一个按钮来启动Add to home screen
提示符。
根据指南,添加此侦听器。
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;
// Update UI notify the user they can add to home screen
btnAdd.style.display = 'block';
});
然后..。用户需要单击该按钮,然后您就可以运行此代码。
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;
});
});
我很容易地将它转换为react组件,下面的代码是从我的Redux项目中删减的,所以它不会复制/粘贴,但应该给出一般的想法。
import React, { Component } from 'react'
import Button from '@material-ui/core/Button'
class AddToHomeScreen extends Component {
constructor (props) {
super(props)
this.deferredPrompt = null
this.state = {
show: false
}
}
componentDidMount () {
var component = this
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.
component.deferredPrompt = e
// Show button
console.log('beforeinstallprompt triggered... show add button')
component.setState({ show: true })
})
}
// bind to this
handleAddClick () {
if (this.deferredPrompt) {
this.setState({ show: false })
// Show the prompt
this.deferredPrompt.prompt()
// Wait for the user to respond to the prompt
this.deferredPrompt.userChoice.then(choiceResult => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt')
} else {
console.log('User dismissed the A2HS prompt')
}
this.deferredPrompt = null
})
} else {
console.log('Invalid prompt object')
}
}
render () {
const { show } = this.state
if (!show) return null
return (
<div className={classes.root}>
<Button variant="contained" onClick={this.handleAddClick.bind(this)}>
Add to home screen
</Button>
</div>
)
}
}
export default AddToHomeScreen
参考资料:https://developers.google.com/web/fundamentals/app-install-banners/
https://stackoverflow.com/questions/21018750
复制相似问题