Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular catch beforeinstallprompt event, add to homescreen in dev tools > application not doing anything

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!

like image 521
john geo Avatar asked Dec 20 '18 15:12

john geo


1 Answers

For Angular following code works for me:

you can test with Google Chrome developer tools

app.component.ts

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

like image 52
Abhay Avatar answered Sep 28 '22 12:09

Abhay