Skip to content

[firebase_messaging] Incorrect HTML example for firebase-messaging-sw.js registration in Flutter Web documentation #17837

@klkucaj

Description

@klkucaj

In the Firebase Cloud Messaging documentation for Flutter Web (https://firebase.google.com/docs/cloud-messaging/receive-messages?platform=flutter), the example provided shows this snippet:

<script src="flutter_bootstrap.js" async>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register('firebase-messaging-sw.js', {
        scope: '/firebase-cloud-messaging-push-scope',
      });
    });
  }
</script>

This example is incorrect because any inline JavaScript inside a <script> tag with a src attribute is ignored by browsers.
As a result, the service worker registration never runs.

Correct version:

<script src="flutter_bootstrap.js" async></script>

<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register('firebase-messaging-sw.js', {
        scope: '/firebase-cloud-messaging-push-scope',
      });
    });
  }
</script>

Suggested Fix:
Update the documentation to separate the inline JavaScript into its own <script> block, ensuring developers correctly register their Firebase Messaging service worker.

Impact:
Following the current example results in firebase-messaging-sw.js not being registered, breaking FCM functionality on Flutter Web.

Additional Observation

Even without manually adding this registration snippet, the firebase_messaging Flutter plugin automatically attempts to register firebase-messaging-sw.js.

If the file doesn’t exist, you’ll see an error like:

[firebase_messaging/failed-service-worker-registration]
Messaging: We are unable to register the default service worker.
Failed to register a ServiceWorker for scope ('http://localhost:7395/firebase-cloud-messaging-push-scope')
with script ('http://localhost:7395/firebase-messaging-sw.js'):
The script has an unsupported MIME type ('text/html').

This suggests the library itself handles service worker registration internally — and the documentation snippet may no longer be necessary in recent versions.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions