diff --git a/LittleShop/wwwroot/js/notifications.js b/LittleShop/wwwroot/js/notifications.js index 42cdcff..145cb1f 100644 --- a/LittleShop/wwwroot/js/notifications.js +++ b/LittleShop/wwwroot/js/notifications.js @@ -113,6 +113,30 @@ class AdminNotificationManager { // Complete setup await this.setupOrderNotifications(); + } catch (error) { + console.error('Failed to enable notifications:', error); + + // Show enhanced error message with diagnostics + let errorMessage = 'āŒ Failed to enable push notifications.\n\n'; + + if (error.message.includes('timed out') && error.message.includes('FCM')) { + errorMessage += 'šŸ”— Network Issue Detected:\n'; + errorMessage += 'Your browser cannot connect to Chrome\'s push notification service (FCM). '; + errorMessage += 'This commonly happens with:\n'; + errorMessage += '• Corporate firewalls or VPNs\n'; + errorMessage += '• Network security software\n'; + errorMessage += '• Restricted internet connections\n\n'; + errorMessage += 'šŸ’” Workarounds:\n'; + errorMessage += '• Try from a different network\n'; + errorMessage += '• Disable VPN temporarily\n'; + errorMessage += '• Contact your IT department\n'; + errorMessage += '• Use a mobile hotspot to test\n\n'; + errorMessage += 'The admin panel will still work normally - you just won\'t receive push notifications.'; + } else { + errorMessage += `Error: ${error.message}`; + } + + this.showNotificationError(errorMessage); } finally { button.disabled = false; button.innerHTML = originalText; diff --git a/LittleShop/wwwroot/js/pwa.js b/LittleShop/wwwroot/js/pwa.js index 5b182bb..cc86a8a 100644 --- a/LittleShop/wwwroot/js/pwa.js +++ b/LittleShop/wwwroot/js/pwa.js @@ -326,17 +326,21 @@ class PWAManager { if (Notification.permission === 'denied') { throw new Error('Notification permission was denied. Please enable notifications in your browser settings.'); } - + // Request notification permission if not already granted let permission = Notification.permission; if (permission === 'default') { permission = await Notification.requestPermission(); } - + if (permission !== 'granted') { throw new Error('Notification permission is required for push notifications. Please allow notifications and try again.'); } + // Enhanced connectivity diagnostics + console.log('PWA: Running push service connectivity diagnostics...'); + await this.runConnectivityDiagnostics(); + // Subscribe to push notifications with enhanced debugging console.log('PWA: Requesting push subscription from browser...'); console.log('PWA: VAPID public key (first 32 chars):', this.vapidPublicKey.substring(0, 32) + '...'); @@ -345,13 +349,14 @@ class PWAManager { let subscription; try { + // Try shorter timeout first to fail faster subscription = await Promise.race([ this.swRegistration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.urlBase64ToUint8Array(this.vapidPublicKey) }), new Promise((_, reject) => - setTimeout(() => reject(new Error('Browser push subscription timed out after 30 seconds. This may indicate an issue with your browser\'s push service connectivity.')), 30000) + setTimeout(() => reject(new Error('Browser push subscription timed out after 15 seconds. This usually indicates a network connectivity issue with Chrome\'s Firebase Cloud Messaging (FCM) service.')), 15000) ) ]); @@ -361,7 +366,10 @@ class PWAManager { } catch (subscriptionError) { console.error('PWA: Browser subscription failed:', subscriptionError); - throw new Error(`Failed to subscribe with browser push service: ${subscriptionError.message}`); + + // Show enhanced error with diagnostics + const diagnosticsInfo = await this.getDiagnosticsInfo(); + throw new Error(`Failed to subscribe with browser push service: ${subscriptionError.message}\n\nDiagnostics:\n${diagnosticsInfo}`); } // Send subscription to server with timeout @@ -572,6 +580,75 @@ class PWAManager { } } + async runConnectivityDiagnostics() { + try { + console.log('PWA: Testing network connectivity...'); + + // Test basic internet connectivity + const startTime = Date.now(); + const response = await fetch('https://www.google.com/generate_204', { + method: 'HEAD', + cache: 'no-cache', + timeout: 5000 + }); + const latency = Date.now() - startTime; + + console.log(`PWA: Internet connectivity: ${response.ok ? 'OK' : 'FAILED'} (${latency}ms)`); + + // Test FCM endpoint accessibility + try { + const fcmResponse = await fetch('https://fcm.googleapis.com/fcm/send', { + method: 'HEAD', + cache: 'no-cache', + timeout: 5000 + }); + console.log(`PWA: FCM service accessibility: ${fcmResponse.status === 404 ? 'OK' : 'UNKNOWN'}`); + } catch (fcmError) { + console.log('PWA: FCM service accessibility: BLOCKED or TIMEOUT'); + } + + } catch (error) { + console.log('PWA: Network diagnostics failed:', error.message); + } + } + + async getDiagnosticsInfo() { + const info = []; + + // Browser info + info.push(`Browser: ${navigator.userAgent}`); + info.push(`Connection: ${navigator.onLine ? 'Online' : 'Offline'}`); + + // Service Worker info + if ('serviceWorker' in navigator) { + info.push(`Service Worker: Supported`); + if (this.swRegistration) { + info.push(`SW State: ${this.swRegistration.active ? 'Active' : 'Inactive'}`); + } + } else { + info.push(`Service Worker: Not Supported`); + } + + // Push Manager info + if ('PushManager' in window) { + info.push(`Push Manager: Supported`); + } else { + info.push(`Push Manager: Not Supported`); + } + + // Notification permission + info.push(`Notification Permission: ${Notification.permission}`); + + // Network info (if available) + if ('connection' in navigator) { + const conn = navigator.connection; + info.push(`Network Type: ${conn.effectiveType || 'Unknown'}`); + info.push(`Network Speed: ${conn.downlink || 'Unknown'}Mbps`); + } + + return info.join('\n- '); + } + // Helper function to convert VAPID key urlBase64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); @@ -597,4 +674,27 @@ window.pwaManager = pwaManager; window.showNotification = (title, options) => pwaManager.showNotification(title, options); window.sendTestPushNotification = () => pwaManager.sendTestNotification(); window.subscribeToPushNotifications = () => pwaManager.subscribeToPushNotifications(); -window.unsubscribeFromPushNotifications = () => pwaManager.unsubscribeFromPushNotifications(); \ No newline at end of file +window.unsubscribeFromPushNotifications = () => pwaManager.unsubscribeFromPushNotifications(); + +// Add console helper for diagnostics +window.testPushConnectivity = async function() { + console.log('šŸ” Running Push Notification Connectivity Test...'); + + if (!window.pwaManager) { + console.log('āŒ PWA Manager not initialized'); + return; + } + + try { + await window.pwaManager.runConnectivityDiagnostics(); + const diagnostics = await window.pwaManager.getDiagnosticsInfo(); + console.log('\nšŸ“Š System Diagnostics:'); + console.log('- ' + diagnostics.split('\n- ').join('\n- ')); + + console.log('\nšŸ’” To test manually, run:'); + console.log('navigator.serviceWorker.register("/service-worker.js").then(reg => reg.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: window.pwaManager.urlBase64ToUint8Array("BDJtQu7zV0H3KF4FkrZ8nPwP3YD_3cEz3hqJvQ6L_gvNpG8ANksQB-FZy2-PDmFAu6duiN4p3mkcNAGnN4YRbws")}))'); + + } catch (error) { + console.log('āŒ Diagnostics failed:', error.message); + } +}; \ No newline at end of file