86 lines
2.3 KiB
TypeScript
86 lines
2.3 KiB
TypeScript
import {
|
||
Directive,
|
||
ElementRef,
|
||
HostListener,
|
||
OnInit,
|
||
Renderer2,
|
||
} from '@angular/core';
|
||
import { MessageService } from 'primeng/api';
|
||
|
||
@Directive({
|
||
selector: '[appDownloadApp]',
|
||
})
|
||
export class DownloadAppDirective implements OnInit {
|
||
public deviceType: 'ios' | 'android' | null = null;
|
||
public deferredPrompt: any;
|
||
|
||
constructor(
|
||
private messageService: MessageService,
|
||
public renderer: Renderer2,
|
||
private el: ElementRef
|
||
) {}
|
||
|
||
ngOnInit(): void {
|
||
this.getTypeDevice();
|
||
if (this.deviceType === 'ios') {
|
||
this.el.nativeElement.style.display = 'block';
|
||
}
|
||
}
|
||
|
||
@HostListener('window:beforeinstallprompt', ['$event'])
|
||
onBeforeInstallPrompt(e: any) {
|
||
e.preventDefault();
|
||
this.deferredPrompt = e;
|
||
if (this.deferredPrompt) {
|
||
this.el.nativeElement.style.display = 'block';
|
||
}
|
||
}
|
||
|
||
@HostListener('window:appinstalled', ['$event'])
|
||
onAppInstalled(e: any) {
|
||
// 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.el.nativeElement.style.display = 'none';
|
||
}
|
||
|
||
getTypeDevice() {
|
||
const userAgent = window.navigator.userAgent.toLowerCase();
|
||
const ios = /iphone|ipod|ipad/.test(userAgent);
|
||
this.deviceType = ios ? 'ios' : 'android';
|
||
}
|
||
|
||
@HostListener('click', ['$event'])
|
||
downloadApp(event: MouseEvent) {
|
||
if (event) {
|
||
event.preventDefault();
|
||
}
|
||
if (this.deviceType === 'ios') {
|
||
this.messageService.add({
|
||
severity: 'custom',
|
||
summary: `Для установки нажмите на кнопку поделиться в Вашем браузере и выберите пункт 'На экран «Домой»'`,
|
||
life: 5000,
|
||
});
|
||
return;
|
||
}
|
||
if (!this.deferredPrompt) {
|
||
this.messageService.add({
|
||
severity: 'error',
|
||
summary: 'Не поддерживается в Вашем браузере!',
|
||
});
|
||
return;
|
||
}
|
||
this.deferredPrompt.prompt();
|
||
this.deferredPrompt.userChoice.then((res: any) => {
|
||
if (res.outcome === 'accepted') {
|
||
this.messageService.add({
|
||
severity: 'custom',
|
||
summary: 'Спасибо за установку!',
|
||
});
|
||
}
|
||
this.deferredPrompt = null;
|
||
});
|
||
}
|
||
}
|