I\'ve created a mobile-friendly web site with jQuery Mobile and added some meta info so that it should be pinned to iOS and Android homescreens and should be launched as a w
The guide indicates that as of Chrome 68 it is expected that the app developer adds a button to their app. And that it should only work if the PWA criteria are met. Then you should be able to use the following code to get a callback to your app where you can show a button to the user to kick off the Add to home screen prompt.
Per the guide, add this listener.
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';
});
Then.... the user needs to click the button, after which you can run this code.
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;
});
});
I converted this to a react component fairly easily, the code below is cut down from my Redux project, so it will not work copy/paste, but should give the general idea.
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 (
)
}
}
export default AddToHomeScreen
References: https://developers.google.com/web/fundamentals/app-install-banners/