NoteJS/public/pwa.js
Fovway 9ecc787719 Обновлены зависимости и улучшена поддержка PWA
- Добавлена библиотека pngjs для работы с PNG изображениями
- Добавлены мета-теги для улучшения поддержки PWA на страницах: index.html, notes.html, profile.html, register.html
- Обновлен сервисный работник для улучшенного кэширования и обработки запросов
- Добавлены функции для отладки PWA в консоли
2025-10-20 09:09:45 +07:00

193 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PWA Service Worker Registration и установка
class PWAManager {
constructor() {
this.deferredPrompt = null;
this.init();
}
init() {
console.log('PWA Manager инициализирован');
this.registerServiceWorker();
this.setupInstallPrompt();
this.setupAppInstalled();
this.checkPWARequirements();
}
// Проверка требований PWA
checkPWARequirements() {
console.log('Проверка требований PWA:');
console.log('- Service Worker:', 'serviceWorker' in navigator);
console.log('- HTTPS:', location.protocol === 'https:' || location.hostname === 'localhost');
console.log('- Manifest:', document.querySelector('link[rel="manifest"]') !== null);
console.log('- Icons:', document.querySelector('link[rel="icon"]') !== null);
}
// Регистрация Service Worker
registerServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then((registration) => {
console.log('SW зарегистрирован успешно:', registration.scope);
// Проверяем обновления
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
this.showUpdateNotification();
}
});
});
})
.catch((error) => {
console.log('Ошибка регистрации SW:', error);
});
});
} else {
console.log('Service Worker не поддерживается');
}
}
// Показ уведомления об обновлении
showUpdateNotification() {
if (confirm('Доступна новая версия приложения. Обновить?')) {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({ type: 'SKIP_WAITING' });
}
window.location.reload();
}
}
// Настройка промпта установки
setupInstallPrompt() {
window.addEventListener('beforeinstallprompt', (e) => {
console.log('beforeinstallprompt событие получено');
e.preventDefault();
this.deferredPrompt = e;
this.showInstallButton();
});
}
// Показ кнопки установки
showInstallButton() {
console.log('Попытка показать кнопку установки');
// Проверяем, не установлено ли уже приложение
if (this.isPWAInstalled()) {
console.log('Приложение уже установлено');
return;
}
const installButton = this.createInstallButton();
this.addInstallButtonToPage(installButton);
}
// Создание кнопки установки
createInstallButton() {
const installButton = document.createElement('button');
installButton.textContent = '📱 Установить приложение';
installButton.className = 'btnSave';
installButton.style.marginTop = '10px';
installButton.style.width = '100%';
installButton.style.fontSize = '14px';
installButton.id = 'pwa-install-button';
installButton.addEventListener('click', () => {
this.installApp();
});
return installButton;
}
// Добавление кнопки на страницу
addInstallButtonToPage(installButton) {
// Удаляем существующую кнопку, если есть
const existingButton = document.getElementById('pwa-install-button');
if (existingButton) {
existingButton.remove();
}
// Ищем подходящее место для кнопки
const authLink = document.querySelector('.auth-link');
const footer = document.querySelector('.footer');
const container = document.querySelector('.container');
if (authLink) {
authLink.appendChild(installButton);
console.log('Кнопка установки добавлена в auth-link');
} else if (footer) {
footer.insertBefore(installButton, footer.firstChild);
console.log('Кнопка установки добавлена в footer');
} else if (container) {
container.appendChild(installButton);
console.log('Кнопка установки добавлена в container');
} else {
document.body.appendChild(installButton);
console.log('Кнопка установки добавлена в body');
}
}
// Установка приложения
installApp() {
console.log('Попытка установки приложения');
if (this.deferredPrompt) {
this.deferredPrompt.prompt();
this.deferredPrompt.userChoice.then((choiceResult) => {
console.log('Результат установки:', choiceResult.outcome);
if (choiceResult.outcome === 'accepted') {
console.log('Пользователь установил приложение');
}
this.deferredPrompt = null;
this.removeInstallButton();
});
} else {
console.log('deferredPrompt не доступен');
}
}
// Удаление кнопки установки
removeInstallButton() {
const installButton = document.getElementById('pwa-install-button');
if (installButton) {
installButton.remove();
console.log('Кнопка установки удалена');
}
}
// Обработка успешной установки
setupAppInstalled() {
window.addEventListener('appinstalled', () => {
console.log('PWA установлено успешно');
this.removeInstallButton();
});
}
// Проверка статуса PWA
isPWAInstalled() {
return window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true;
}
// Получение информации о PWA
getPWAInfo() {
return {
isInstalled: this.isPWAInstalled(),
isOnline: navigator.onLine,
hasServiceWorker: 'serviceWorker' in navigator,
userAgent: navigator.userAgent,
hasDeferredPrompt: this.deferredPrompt !== null
};
}
}
// Инициализация PWA Manager
const pwaManager = new PWAManager();
// Экспорт для использования в других скриптах
window.PWAManager = pwaManager;
// Добавляем глобальную функцию для отладки
window.debugPWA = () => {
console.log('PWA Debug Info:', pwaManager.getPWAInfo());
};