firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.73k stars 3.98k forks source link

firebase messaging problem! #13238

Closed 0wwafa closed 2 months ago

0wwafa commented 3 months ago

Is there an existing issue for this?

Which plugins are affected?

Messaging

Which platforms are affected?

Web

Description

i have this test code in my index.html:

  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
  <script>
    // Initialize Firebase
    const firebaseConfig = {
[.......]
    };

    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
    const database = firebase.database();

    // Group ID and user ID (replace with unique identifiers)
    let groupId = '';
    const userId = 'user' + Math.floor(Math.random() * 1000);

    // Join group
    function joinGroup() {
      groupId = document.getElementById('groupId').value;
      if (groupId) {
        // Subscribe to the group topic
        messaging.subscribeToTopic(groupId)
          .then(() => console.log('Subscribed to topic:', groupId))
          .catch(error => console.error('Error subscribing to topic:', error));

        // Update online presence in the database
        const presenceRef = database.ref(`groups/${groupId}/online/${userId}`);
        presenceRef.set(true);
        presenceRef.onDisconnect().remove(); // Remove presence on disconnect

        // Fetch and display online members
        database.ref(`groups/${groupId}/online`).on('value', snapshot => {
          const onlineMembers = snapshot.val() || {};
          displayOnlineMembers(onlineMembers);
        });
      }
    }

    // Send message
    function sendMessage() {
      const message = document.getElementById('message').value;
      if (message && groupId) {
        messaging.sendToTopic(groupId, {
          notification: {
            title: `User ${userId}`,
            body: message
          }
        })
        .then(() => console.log('Message sent!'))
        .catch(error => console.error('Error sending message:', error));
      }
    }

    // Display online members
    function displayOnlineMembers(members) {
      const onlineList = document.getElementById('onlineList');
      onlineList.innerHTML = '';
      for (const memberId in members) {
        const listItem = document.createElement('li');
        listItem.textContent = memberId;
        onlineList.appendChild(listItem);
      }
    }

    // Request notification permission
    Notification.requestPermission().then(permission => {
      if (permission === 'granted') {
        // Get the registration token
        messaging.getToken().then(token => {
          console.log('Registration token:', token);
        });
      }
    });

    // Listen for incoming messages
    messaging.onMessage(payload => {
      console.log('Message received:', payload);
      showNotification(payload.notification.title, payload.notification.body);
    });

    function showNotification(title, body) {
      new Notification(title, { body });
    }

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('./firebase-messaging-sw.js', { scope: './' })
      .then(registration => {
        console.log('Service worker registered:', registration);
      })
      .catch(error => {
        console.error('Service worker registration failed:', error);
      });
  });
}

the serviceworker registers in the browser. but I get this error from messaging:

Uncaught (in promise) FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('[https://MYWEBSITE/firebase-cloud-messaging-push-scope](https://www.google.com/url?sa=E&q=https%3A%2F%2Fqsd.zibri.org%2Ffirebase-cloud-messaging-push-scope)') with script ('[https://MYWEBSITE/firebase-messaging-sw.js](https://www.google.com/url?sa=E&q=https%3A%2F%2Fqsd.zibri.org%2Ffirebase-messaging-sw.js)'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
at nt.<anonymous> (window-controller.ts:166:27)
at tslib.es6.js:102:23
at Object.throw (tslib.es6.js:83:53)
at i (tslib.es6.js:74:64)

but the address of the webapp is https://MYWEBSITE/MYAPP/firebase-messaging-sw.js

in the directory: https://MYWEBSITE/MYAPP/ both index.html and firebase-messaging-sw.js are present!

Reproducing the issue

just copy the code above.

Firebase Core version

8.10.1

Flutter Version

0.0.0.0

Relevant Log Output

No response

Flutter dependencies

Expand Flutter dependencies snippet
```yaml Replace this line with the contents of your `flutter pub deps -- --style=compact`. ```

not a flutter problem

Additional context and comments

No response

SelaseKay commented 2 months ago

Hi @0wwafa . Thanks for the report. I'm not entirely sure on what you're trying to achieve. Are you trying to setup firebase for flutter web?

0wwafa commented 2 months ago

Hi @0wwafa . Thanks for the report. I'm not entirely sure on what you're trying to achieve. Are you trying to setup firebase for flutter web?

I wish to be able to send push notifications from one webapp to another.

SelaseKay commented 2 months ago

Hi @0wwafa , This issue seems to be out of scope for this repo. It should be worth reporting here