class PWAInstallPrompt { constructor() { this.deferredPrompt = null; this.isInstalled = false; this.installButton = null; this.installBanner = null; this.dismissedCount = 0; this.maxDismissals = 3; this.installationChecked = false; this.init(); } init() { console.log('💿 PWA Install Prompt initializing...'); this.checkInstallationStatus(); this.setupEventListeners(); this.createInstallButton(); this.loadInstallPreferences(); // Проверяем статус установки периодически для iOS if (this.isIOSSafari()) { this.startInstallationMonitoring(); } console.log('✅ PWA Install Prompt initialized'); } checkInstallationStatus() { // Проверяем различные способы определения установки PWA const isStandalone = window.matchMedia('(display-mode: standalone)').matches; const isIOSStandalone = window.navigator.standalone === true; const hasInstallPreference = this.loadInstallPreferences().installed; // Проверяем, установлено ли приложение if (isStandalone || isIOSStandalone || hasInstallPreference) { this.isInstalled = true; console.log('📱 App is already installed as PWA'); document.body.classList.add('pwa-installed'); // Скрываем все промпты установки this.hideInstallPrompts(); // Если это iOS, добавляем специальный класс if (this.isIOSSafari()) { document.body.classList.add('ios-pwa'); } this.installationChecked = true; return true; } // Если не установлено, добавляем соответствующие классы document.body.classList.add('pwa-browser'); if (this.isIOSSafari()) { document.body.classList.add('ios-safari'); } this.installationChecked = true; return false; } startInstallationMonitoring() { // Для iOS Safari мониторим изменения в standalone режиме let wasStandalone = window.navigator.standalone; const checkStandalone = () => { const isStandalone = window.navigator.standalone; if (isStandalone && !wasStandalone && !this.isInstalled) { console.log('✅ iOS PWA installation detected'); this.isInstalled = true; this.hideInstallPrompts(); this.showInstallSuccess(); document.body.classList.remove('pwa-browser'); document.body.classList.add('pwa-installed', 'ios-pwa'); // Сохраняем предпочтение установки this.saveInstallPreference('installed', true); } wasStandalone = isStandalone; }; // Проверяем каждые 2 секунды setInterval(checkStandalone, 2000); // Также проверяем при изменении видимости страницы window.addEventListener('visibilitychange', () => { if (!document.hidden) { setTimeout(checkStandalone, 1000); } }); } setupEventListeners() { window.addEventListener('beforeinstallprompt', (event) => { console.log('💿 Install prompt event captured'); event.preventDefault(); this.deferredPrompt = event; // Показываем промпт только если приложение не установлено if (!this.isInstalled && this.shouldShowPrompt()) { this.showInstallOptions(); } }); window.addEventListener('appinstalled', () => { console.log('✅ PWA installed successfully'); this.isInstalled = true; this.hideInstallPrompts(); this.showInstallSuccess(); this.saveInstallPreference('installed', true); document.body.classList.remove('pwa-browser'); document.body.classList.add('pwa-installed'); }); // Дополнительная проверка для iOS if (this.isIOSSafari()) { let wasStandalone = window.navigator.standalone; window.addEventListener('visibilitychange', () => { if (document.hidden) return; setTimeout(() => { const isStandalone = window.navigator.standalone; if (isStandalone && !wasStandalone && !this.isInstalled) { console.log('✅ iOS PWA installation detected'); this.isInstalled = true; this.hideInstallPrompts(); this.showInstallSuccess(); document.body.classList.remove('pwa-browser'); document.body.classList.add('pwa-installed', 'ios-pwa'); // Сохраняем предпочтение установки this.saveInstallPreference('installed', true); } wasStandalone = isStandalone; }, 1000); }); } } createInstallButton() { this.installButton = document.createElement('button'); this.installButton.id = 'pwa-install-button'; this.installButton.className = 'hidden fixed bottom-6 right-6 bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white px-6 py-3 rounded-full shadow-lg transition-all duration-300 z-50 flex items-center space-x-3 group'; const buttonText = this.isIOSSafari() ? 'Install App' : 'Install App'; const buttonIcon = this.isIOSSafari() ? 'fas fa-share' : 'fas fa-download'; this.installButton.innerHTML = ` ${buttonText}
`; this.installButton.addEventListener('click', () => { this.handleInstallClick(); }); document.body.appendChild(this.installButton); } createInstallBanner() { if (this.installBanner) return; this.installBanner = document.createElement('div'); this.installBanner.id = 'pwa-install-banner'; this.installBanner.className = 'pwa-install-banner fixed bottom-0 left-0 right-0 transform translate-y-full transition-transform duration-300 z-40'; this.installBanner.innerHTML = `
Install SecureBit.chat
Get the native app experience with enhanced security
`; // Handle banner actions this.installBanner.addEventListener('click', (event) => { const action = event.target.closest('[data-action]')?.dataset.action; if (action === 'install') { this.handleInstallClick(); } else if (action === 'dismiss') { this.dismissInstallPrompt(); } }); document.body.appendChild(this.installBanner); } showInstallOptions() { // Дополнительная проверка статуса установки if (!this.installationChecked) { this.checkInstallationStatus(); } if (this.isInstalled) { console.log('💿 App is already installed, not showing install options'); return; } if (this.isIOSSafari()) { this.showInstallButton(); } else if (this.isMobileDevice()) { this.showInstallBanner(); } else { this.showInstallButton(); } } showInstallButton() { // Дополнительная проверка статуса установки if (!this.installationChecked) { this.checkInstallationStatus(); } if (this.installButton && !this.isInstalled) { this.installButton.classList.remove('hidden'); // Add entrance animation setTimeout(() => { this.installButton.style.transform = 'scale(1.1)'; setTimeout(() => { this.installButton.style.transform = 'scale(1)'; }, 200); }, 100); console.log('💿 Install button shown'); } else { console.log('💿 Install button not shown - app is installed or button not available'); } } showInstallBanner() { // Дополнительная проверка статуса установки if (!this.installationChecked) { this.checkInstallationStatus(); } if (this.isInstalled) { console.log('💿 App is installed, not showing install banner'); return; } if (!this.installBanner) { this.createInstallBanner(); } if (this.installBanner && !this.isInstalled) { setTimeout(() => { this.installBanner.classList.add('show'); this.installBanner.style.transform = 'translateY(0)'; }, 1000); console.log('💿 Install banner shown'); } else { console.log('💿 Install banner not shown - app is installed or banner not available'); } } hideInstallPrompts() { console.log('💿 Hiding all install prompts'); if (this.installButton) { this.installButton.classList.add('hidden'); console.log('💿 Install button hidden'); } if (this.installBanner) { this.installBanner.classList.remove('show'); this.installBanner.style.transform = 'translateY(100%)'; console.log('💿 Install banner hidden'); } // Устанавливаем флаг установки this.isInstalled = true; } async handleInstallClick() { if (this.isIOSSafari()) { this.showIOSInstallInstructions(); return; } if (!this.deferredPrompt) { console.warn('⚠️ Install prompt not available'); this.showFallbackInstructions(); return; } try { console.log('💿 Showing install prompt...'); const result = await this.deferredPrompt.prompt(); console.log('💿 Install prompt result:', result.outcome); if (result.outcome === 'accepted') { console.log('✅ User accepted install prompt'); this.hideInstallPrompts(); this.saveInstallPreference('accepted', true); } else { console.log('❌ User dismissed install prompt'); this.handleInstallDismissal(); } this.deferredPrompt = null; } catch (error) { console.error('❌ Install prompt failed:', error); this.showFallbackInstructions(); } } showIOSInstallInstructions() { const modal = document.createElement('div'); modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 backdrop-blur-sm'; modal.innerHTML = `

Install on iOS

1
Tap the Share button
Usually at the bottom of Safari
2
Find "Add to Home Screen"
Scroll down in the share menu
3
Tap "Add"
Confirm to install SecureBit.chat

After installation, open SecureBit from your home screen for the best experience.

`; // Добавляем обработчики событий для кнопок const gotItBtn = modal.querySelector('.got-it-btn'); const laterBtn = modal.querySelector('.later-btn'); gotItBtn.addEventListener('click', () => { modal.remove(); localStorage.setItem('ios_install_shown', Date.now()); this.saveInstallPreference('ios_instructions_shown', Date.now()); console.log('✅ iOS install instructions acknowledged'); }); laterBtn.addEventListener('click', () => { modal.remove(); localStorage.setItem('ios_install_dismissed', Date.now()); this.dismissedCount++; this.saveInstallPreference('dismissed', this.dismissedCount); console.log('❌ iOS install instructions dismissed'); }); document.body.appendChild(modal); this.saveInstallPreference('ios_instructions_shown', Date.now()); } showFallbackInstructions() { const modal = document.createElement('div'); modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 backdrop-blur-sm'; modal.innerHTML = `

Install SecureBit.chat

To install this app, look for the install option in your browser menu or address bar. Different browsers have different install methods.

Chrome/Edge
Look for install icon in address bar
Firefox
Add bookmark to home screen
Safari
Share → Add to Home Screen
`; // Добавляем обработчик события для кнопки Close const closeBtn = modal.querySelector('.close-btn'); closeBtn.addEventListener('click', () => { modal.remove(); console.log('📱 Fallback install instructions closed'); }); document.body.appendChild(modal); } showInstallSuccess() { console.log('✅ Showing installation success notification'); const notification = document.createElement('div'); notification.className = 'fixed top-4 right-4 bg-green-500 text-white p-4 rounded-lg shadow-lg z-50 max-w-sm transform translate-x-full transition-transform duration-300'; const successText = this.isIOSSafari() ? 'iOS App installed! Open from home screen.' : 'SecureBit.chat is now on your device'; notification.innerHTML = `
App Installed!
${successText}
`; document.body.appendChild(notification); setTimeout(() => { notification.classList.remove('translate-x-full'); }, 100); setTimeout(() => { notification.classList.add('translate-x-full'); setTimeout(() => notification.remove(), 300); }, 5000); // Скрываем все промпты установки this.hideInstallPrompts(); } shouldShowPrompt() { // Если приложение уже установлено, не показываем промпт if (this.isInstalled) { console.log('💿 App is already installed, not showing install prompt'); return false; } // Дополнительная проверка статуса установки if (!this.installationChecked) { this.checkInstallationStatus(); } // Если после проверки приложение установлено, не показываем промпт if (this.isInstalled) { console.log('💿 App installation confirmed, not showing install prompt'); return false; } const preferences = this.loadInstallPreferences(); // Проверяем, не было ли приложение уже установлено if (preferences.installed) { console.log('💿 Installation preference found, not showing install prompt'); this.isInstalled = true; return false; } if (this.isIOSSafari()) { const lastShown = preferences.ios_instructions_shown; const lastDismissed = localStorage.getItem('ios_install_dismissed'); if (lastShown && Date.now() - lastShown < 24 * 60 * 60 * 1000) { return false; } if (lastDismissed && Date.now() - parseInt(lastDismissed) < 7 * 24 * 60 * 60 * 1000) { return false; } return true; } if (preferences.dismissed >= this.maxDismissals) return false; const lastDismissed = preferences.lastDismissed; if (lastDismissed && Date.now() - lastDismissed < 24 * 60 * 60 * 1000) { return false; } return true; } dismissInstallPrompt() { this.dismissedCount++; this.hideInstallPrompts(); this.saveInstallPreference('dismissed', this.dismissedCount); console.log(`💿 Install prompt dismissed (${this.dismissedCount}/${this.maxDismissals})`); // Show encouraging message on final dismissal if (this.dismissedCount >= this.maxDismissals) { this.showFinalDismissalMessage(); } } handleInstallDismissal() { this.dismissedCount++; this.saveInstallPreference('dismissed', this.dismissedCount); if (this.dismissedCount < this.maxDismissals) { setTimeout(() => { if (!this.isInstalled && this.shouldShowPrompt()) { this.showInstallButton(); } }, 300000); } } showFinalDismissalMessage() { const notification = document.createElement('div'); notification.className = 'fixed bottom-4 left-4 right-4 bg-blue-500/90 text-white p-4 rounded-lg shadow-lg z-50 backdrop-blur-sm'; notification.innerHTML = `
Install Anytime
You can still install SecureBit.chat from your browser's menu for the best experience.
`; // Добавляем обработчик события для кнопки OK const okBtn = notification.querySelector('.ok-btn'); okBtn.addEventListener('click', () => { notification.remove(); console.log('✅ Final dismissal message acknowledged'); }); document.body.appendChild(notification); setTimeout(() => { if (notification.parentElement) { notification.remove(); } }, 10000); } saveInstallPreference(action, value) { const preferences = this.loadInstallPreferences(); preferences[action] = value; if (action === 'dismissed') { preferences.lastDismissed = Date.now(); } try { localStorage.setItem('pwa_install_prefs', JSON.stringify(preferences)); } catch (error) { console.warn('⚠️ Could not save install preferences:', error); } } loadInstallPreferences() { try { const saved = localStorage.getItem('pwa_install_prefs'); return saved ? JSON.parse(saved) : { dismissed: 0, installed: false }; } catch (error) { console.warn('⚠️ Could not load install preferences:', error); return { dismissed: 0, installed: false }; } } isMobileDevice() { return /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); } isIOSSafari() { const userAgent = navigator.userAgent; const isIOS = /iPad|iPhone|iPod/.test(userAgent); const isSafari = /Safari/.test(userAgent) && !/CriOS|FxiOS|EdgiOS/.test(userAgent); return isIOS && isSafari; } // Public API methods showInstallPrompt() { if (this.isIOSSafari()) { this.showIOSInstallInstructions(); } else if (this.deferredPrompt && !this.isInstalled) { this.handleInstallClick(); } else { this.showFallbackInstructions(); } } hideInstallPrompt() { this.hideInstallPrompts(); } getInstallStatus() { return { isInstalled: this.isInstalled, canPrompt: !!this.deferredPrompt, isIOSSafari: this.isIOSSafari(), dismissedCount: this.dismissedCount, shouldShowPrompt: this.shouldShowPrompt() }; } resetDismissals() { this.dismissedCount = 0; this.saveInstallPreference('dismissed', 0); console.log('💿 Install dismissals reset'); } // Method for setting service worker registration setServiceWorkerRegistration(registration) { this.swRegistration = registration; console.log('📡 Service Worker registration set for PWA Install Prompt'); } } // Export for module use if (typeof module !== 'undefined' && module.exports) { module.exports = PWAInstallPrompt; } else { window.PWAInstallPrompt = PWAInstallPrompt; } // Auto-initialize if (typeof window !== 'undefined') { window.addEventListener('DOMContentLoaded', () => { if (!window.pwaInstallPrompt) { window.pwaInstallPrompt = new PWAInstallPrompt(); } }); }