Sekrab Garage

Catch beforeinstallprompt

Catch window beforeinstallprompt event as it happens in Angular app.

Angular June 1, 20
Subscribe to Sekrab Parts newsletter.

Writing window.addEventListener('beforeinstallprompt') inside an Angular application does not guarantee it's being caught in time, because the event fires way before the app is fully loaded. To catch the event properly, add the listner to the root component: App.Component, update a shared service subject, then listen to that subject anywhere else.

App.component.ts

window.addEventListener('beforeinstallprompt', (e) => {
   this.windowEventsService.fire(e);
});

Windoweventsservice.ts


@Injectable({ providedIn: 'root' })
export class WindowEventsService {

    private windowEventSubject = new BehaviorSubject<any>(null);
    windowEvent = this.windowEventSubject.asObservable();

    fire(e: any) {
        this.windowEventSubject.next(e);
    }
}

Install partial component: (the listener)

this.windowEventsService.windowEvent.subscribe(e => {
  if (!e) {
    return;
  }
  this.deferredPrompt = e;
  // continue as usual with this.deferredPrompt.prompt();
});