"Push-notification-diagnostics-enhancement"

This commit is contained in:
sysadmin 2025-09-30 17:48:23 +01:00
parent 8b4cb6e78c
commit 021cfc4edc
2 changed files with 129 additions and 5 deletions

View File

@ -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;

View File

@ -337,6 +337,10 @@ class PWAManager {
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);
@ -598,3 +675,26 @@ window.showNotification = (title, options) => pwaManager.showNotification(title,
window.sendTestPushNotification = () => pwaManager.sendTestNotification();
window.subscribeToPushNotifications = () => pwaManager.subscribeToPushNotifications();
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);
}
};