67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
|
|
import { Injectable, signal } from '@angular/core';
|
||
|
|
import { ConfirmationService } from 'primeng/api';
|
||
|
|
|
||
|
|
@Injectable({ providedIn: 'root' })
|
||
|
|
export class PwaInstallService {
|
||
|
|
private deferredInstallPrompt: any = null;
|
||
|
|
readonly isInstalled = signal(false);
|
||
|
|
readonly canInstall = signal(false);
|
||
|
|
|
||
|
|
constructor(private readonly confirmationService: ConfirmationService) {
|
||
|
|
this.init();
|
||
|
|
}
|
||
|
|
|
||
|
|
init() {
|
||
|
|
if (typeof window === 'undefined') {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const standalone =
|
||
|
|
window.matchMedia('(display-mode: standalone)').matches ||
|
||
|
|
(window.navigator as any).standalone === true;
|
||
|
|
|
||
|
|
console.log(window.matchMedia('(display-mode: standalone)').matches);
|
||
|
|
console.log(window.navigator);
|
||
|
|
|
||
|
|
this.isInstalled.set(standalone);
|
||
|
|
|
||
|
|
window.addEventListener('beforeinstallprompt', (event: any) => {
|
||
|
|
event.preventDefault();
|
||
|
|
|
||
|
|
this.deferredInstallPrompt = event;
|
||
|
|
this.canInstall.set(true);
|
||
|
|
console.log(this.deferredInstallPrompt);
|
||
|
|
});
|
||
|
|
|
||
|
|
window.addEventListener('appinstalled', () => {
|
||
|
|
this.deferredInstallPrompt = null;
|
||
|
|
this.canInstall.set(false);
|
||
|
|
this.isInstalled.set(true);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
openInstallConfirm() {
|
||
|
|
if (this.isInstalled() || !this.canInstall() || !this.deferredInstallPrompt) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log('openInstallConfirm');
|
||
|
|
|
||
|
|
this.confirmationService.confirm({
|
||
|
|
header: 'نصب اپلیکیشن',
|
||
|
|
message: 'برای ادامه میبایست نیازمندیهای نرمافزار را نصب کنید',
|
||
|
|
acceptLabel: 'نصب',
|
||
|
|
rejectButtonProps: {
|
||
|
|
outlined: true,
|
||
|
|
},
|
||
|
|
accept: () => {
|
||
|
|
this.deferredInstallPrompt.prompt();
|
||
|
|
this.deferredInstallPrompt.userChoice.finally(() => {
|
||
|
|
this.deferredInstallPrompt = null;
|
||
|
|
this.canInstall.set(false);
|
||
|
|
});
|
||
|
|
},
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|