You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 3 PWA集成Firebase Cloud Messaging遇404错误求助

Fixing the 404 Error for Default Service Worker in Ionic 3 PWA + FCM Integration

Hey there! Let's work through that frustrating 404 error you're hitting when trying to integrate FCM with your Ionic 3 PWA. I've dealt with similar issues before, so here are the most likely fixes to get your service worker up and running:

1. Verify Service Worker File Location & Registration Path

First, double-check where your service-worker.js lives and how it's being registered:

  • In Ionic 3, the service worker should end up in the root of your www directory after a production build.
  • Open your index.html and confirm the registration code uses the correct relative path. It should look like this:
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js')
          .then(reg => console.log('Service Worker registered successfully:', reg))
          .catch(err => console.error('Service Worker registration failed:', err));
      });
    }
    
  • Note: Local development with ionic serve might not properly generate the service worker. Always test with ionic serve --prod to mimic production build behavior.

2. Check Ionic's Service Worker Configuration

Make sure Ionic is set to generate and enable the service worker:

  • Open ionic.config.json and verify the serviceWorker section is enabled:
    {
      "name": "your-app-name",
      "app_id": "",
      "type": "ionic-angular",
      "serviceWorker": {
        "enabled": true
      }
    }
    
  • If you manually modified the service-worker.js file, ensure it's based on Ionic's generated template—customizing from scratch can break the built-in caching logic that FCM relies on.

3. Correctly Integrate FCM into the Service Worker

Ensure your FCM setup in service-worker.js is properly structured and uses matching Firebase versions:

  • Add the FCM scripts at the top of your service-worker.js (match the Firebase version to what's in your app's dependencies):
    importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
    
    firebase.initializeApp({
      'messagingSenderId': 'YOUR_FCM_SENDER_ID'
    });
    
    const messaging = firebase.messaging();
    
    // Optional: Handle background messages
    messaging.setBackgroundMessageHandler(payload => {
      const notificationTitle = payload.notification.title;
      const notificationOptions = {
        body: payload.notification.body
      };
      return self.registration.showNotification(notificationTitle, notificationOptions);
    });
    

4. Rebuild Your App to Generate the Service Worker

If the service-worker.js is missing from the www directory after building:

  • Clean your project and rebuild from scratch to ensure all assets are generated correctly:
    rm -rf www node_modules
    npm install
    ionic build --prod
    
  • After the build, check the www folder—you should see the service-worker.js file with your FCM code included.

5. Adjust FCM Initialization Timing

Don't call enableNotifications() until the service worker is fully registered and ready:

  • Update your provider's enableNotifications() method to wait for the service worker to be ready:
    import { Injectable } from '@angular/core';
    import * as firebase from 'firebase';
    
    @Injectable()
    export class FcmProvider {
      messaging: firebase.messaging.Messaging;
    
      constructor() {
        firebase.initializeApp({
          // Your Firebase config
          messagingSenderId: 'YOUR_SENDER_ID'
        });
        this.messaging = firebase.messaging();
      }
    
      enableNotifications() {
        if ('serviceWorker' in navigator) {
          navigator.serviceWorker.ready.then(registration => {
            this.messaging.useServiceWorker(registration);
            // Now request notification permissions and get token
            this.messaging.requestPermission()
              .then(() => this.messaging.getToken())
              .then(token => console.log('FCM Token:', token))
              .catch(err => console.error('FCM permission error:', err));
          });
        }
      }
    }
    

Final Checks

  • Test your app after deploying it to a HTTPS server (service workers require HTTPS, except for localhost).
  • Use Chrome DevTools' Application > Service Workers tab to verify the service worker is registered and active.

内容的提问来源于stack exchange,提问作者Sergey Rudenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:25:06