I want to use the add to homescreen function of pwa's.
I made a pwa of my app and for testing purposes Im using http-server to run it https://www.npmjs.com/package/http-server
When I run audits I get a score of 92. the only fail is "Does not redirect HTTP traffic to HTTPS". But passed audits include: "user can be prompted to Install the Web App" and "Site is served over HTTPS"
in chrome://flags/ I have 'bypass user engagement checks and app banners enabled'
For testing I'm listening to the beforeinstallprompt event, for now, I'm listening to the event in the ngoninit part of my homepage with:
window.addEventListener('beforeinstallprompt', e => {
console.log('beforeinstallprompt Event fired');
});
but when I press "add to home screen" in dev tools, nothing is logged in the console.
How can I catch the beforeinstallprompt-event?
Any help is greatly appreciated!
For Angular following code works for me:
you can test with Google Chrome developer tools
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
template: '<button (click)="addToHomeScreen()" *ngIf="showButton">Add to Home Scree</button>',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
deferredPrompt: any;
showButton = false;
@HostListener('window:beforeinstallprompt', ['$event'])
onbeforeinstallprompt(e) {
console.log(e);
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
this.deferredPrompt = e;
this.showButton = true;
}
addToHomeScreen() {
// hide our user interface that shows our A2HS button
this.showButton = 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;
});
}
}
'onbeforeinstallprompt' event is still not follows web standards
Reference : Add to Home Screen | Google Developers
GitHub Gist link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With