Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot get IOS token first time #8793

Closed
bangluong opened this issue Feb 14, 2025 · 11 comments
Closed

Cannot get IOS token first time #8793

bangluong opened this issue Feb 14, 2025 · 11 comments

Comments

@bangluong
Copy link

bangluong commented Feb 14, 2025

Operating System

IOS 18.3

Environment (if applicable)

safari

Firebase SDK Version

10.14.0

Firebase SDK Product(s)

Messaging

Project Tooling

reactJS and webpack

Detailed Problem Description

I create requestPermission and get token after login.
after iphone ask permission to push notification, I got error browser not supported.

but if I logout and login again it get token successfully

Steps and code to reproduce issue

here is my code:

const messaging = (async () => {
    const isSupportedBrowser = await isSupported();

    if (isSupportedBrowser) {
        return getMessaging(firebase);
    }
    return null;
})
export const getMessagingToken = async () => {
    let currentToken = "";
    const messagingResolve = await messaging();
    if (!messagingResolve) return;
    try {
        currentToken = await getToken(messagingResolve, {
            vapidKey: process.env.FIREBASE_VAPIDKEY
        });
    } catch (error) {
        console.log("An error occurred while retrieving token. ", error);
    }
    return currentToken;
};

at login function, I add this code:

if (Notification) {
                    const permission = await Notification.requestPermission();
                    if (permission === "granted") {
                        const firebaseToken = await getMessagingToken();
                        await pushToken({
                            variables: {
                                token: firebaseToken
                            }
                        });
                    }
                }
@bangluong bangluong added new A new issue that hasn't be categoirzed as question, bug or feature request question labels Feb 14, 2025
@google-oss-bot
Copy link
Contributor

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

@jbalidiong jbalidiong added api: messaging needs-attention and removed needs-triage new A new issue that hasn't be categoirzed as question, bug or feature request labels Feb 14, 2025
@hsubox76
Copy link
Contributor

I can't reproduce the error with the code you provided. You say "after iphone ask permission to push notification, I got error browser not supported." but can you specify what line is causing that error? That makes it sound like it's happening on Notiification.requestPermission(), is that correct? Or in getMessagingToken()? Do you have the stack trace of the exact error in your console that would show what line is throwing and when?

Also, what does pushToken() do?

@bangluong
Copy link
Author

I got error when try to get token: Subscribing for push requires an active service worker

pushToken just send token to server

@comxd
Copy link

comxd commented Feb 18, 2025

@bangluong About SW, from the FCM doc:

FCM requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client setup process.

https://firebase.google.com/docs/cloud-messaging/js/client

About your error described in your first message, see #8356

@dlarocque
Copy link
Contributor

I got error when try to get token: Subscribing for push requires an active service worker

@bangluong This error is different from the error you first described in the issue. Are you seeing an error that the browser is not supported, or that the service worker is not active?

Also, you mentioned that 'logout and login again it get token successfully'. Are you using Firebase Auth here? If so, could you please share that code?

@bangluong
Copy link
Author

bangluong commented Feb 19, 2025

@dlarocque what is Firebase Auth? here is my full code:

import { initializeApp } from "firebase/app";
import { getMessaging, getToken, isSupported, onMessage } from "firebase/messaging";

const firebase = initializeApp({
    apiKey: process.env.FIREBASE_API_KEY,
    authDomain: process.env.FIREBASE_AUTH_DOMAIN,
    projectId: process.env.FIREBASE_PROJECT_ID,
    storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.FIREBASE_SENDER_ID,
    appId: process.env.FIREBASE_APP_ID,
    measurementId: process.env.FIREBASE_MERCHANT_ID
});
const messaging = (async () => {
    const isSupportedBrowser = await isSupported();

    if (isSupportedBrowser) {
        return getMessaging(firebase);
    }
    return null;
})
export const getMessagingToken = async () => {
    let currentToken = "";
    const messagingResolve = await messaging();
    if (!messagingResolve) return;
    try {
        currentToken = await getToken(messagingResolve, {
            vapidKey: process.env.FIREBASE_VAPIDKEY
        });
    } catch (error) {
        console.log("An error occurred while retrieving token. ", error);
    }
    return currentToken;
};

I checked that currentToken is return "" and I log error.message. it is 'Subscribing for push requires an active service worker'.

@dlarocque
Copy link
Contributor

@dlarocque what is Firebase Auth? here is my full code: `import { initializeApp } from "firebase/app"; import { getMessaging, getToken, isSupported, onMessage } from "firebase/messaging";

const firebase = initializeApp({ apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: process.env.FIREBASE_PROJECT_ID, storageBucket: process.env.FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.FIREBASE_SENDER_ID, appId: process.env.FIREBASE_APP_ID, measurementId: process.env.FIREBASE_MERCHANT_ID }); const messaging = (async () => { const isSupportedBrowser = await isSupported();

if (isSupportedBrowser) {
    return getMessaging(firebase);
}
return null;

}) export const getMessagingToken = async () => { let currentToken = ""; const messagingResolve = await messaging(); if (!messagingResolve) return; try { currentToken = await getToken(messagingResolve, { vapidKey: process.env.FIREBASE_VAPIDKEY }); } catch (error) { console.log("An error occurred while retrieving token. ", error); } return currentToken; };`

I checked that currentToken is return "" and I log error.message. it is 'Subscribing for push requires an active service worker'.

@bangluong When I run this code, the registration is successful and I get a token. Please share more information that would help us reproduce this issue. Do you see this error in the desktop browse Chrome/Safari? Or is it only on mobile browsers?

@bangluong
Copy link
Author

@dlarocque this error is in iphone safari.
it only on mobile. I use magento 2 pwa studio for FE.

@dlarocque
Copy link
Contributor

dlarocque commented Mar 12, 2025

@bangluong I have tested your snippets in a React App. I installed the app as a PWA, and registration was successful. iOS Safari only supports Notifications in PWAs, and users must enable it manually since it's still an experimental feature.

  1. Can you confirm that your app is running as a PWA and you've enabled the Push API on your device?
  2. Can you confirm that your service worker is valid? Please share your firebase-messaging-sw.js file.

Here's the code:

firebase-messaging-sw.js:

importScripts('https://www.gstatic.com/firebasejs/10.14.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.14.0/firebase-messaging-compat.js');

firebase.initializeApp({
  /* */
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((event) => {
  console.log('[onBackgroundMessage] Push Received.');
  return self.registration.showNotification('hello', {});
})

App.js:

import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, isSupported, onMessage } from 'firebase/messaging';

const firebaseConfig = {
  /* */
};

const app = initializeApp(firebaseConfig);

const messaging = async() => {
  const isSupportedBrowser = await isSupported();
  
  if (isSupportedBrowser) {
      return getMessaging(app);
  }

  return null;
}

const getMessagingToken = async () => {
  let currentToken = "";
  const messagingResolve = await messaging();
  if (!messagingResolve) {
    console.error("failed to get messaging")
  };

  try {
    currentToken = await getToken(messagingResolve, { vapidKey: /* my vapid key */ }); // Successful. currentToken is defined.
  } catch (error) {
    console.log("An error occurred while retrieving token. ", error);
  }
  return currentToken;
};

const requestPermission = async () => {
  Notification.requestPermission().then(async (permission) => {
    if (permission === 'granted') {
      const token = await getMessagingToken();
    } else {
      console.warn("Notification permission denied");
    }
  })
}

// ... other app code

@google-oss-bot
Copy link
Contributor

Hey @bangluong. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

@google-oss-bot
Copy link
Contributor

Since there haven't been any recent updates here, I am going to close this issue.

@bangluong if you're still experiencing this problem and want to continue the discussion just leave a comment here and we are happy to re-open this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants