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.5k stars 3.92k forks source link

Firebase Messaging: getToken() error on web #13010

Open mklepaczko opened 3 days ago

mklepaczko commented 3 days ago

Is there an existing issue for this?

Which plugins are affected?

Messaging

Which platforms are affected?

Web

Description

FirebaseMessaging.instance.getToken(vapidKey: 'key') throws error on web

Reproducing the issue

FirebaseMessaging messaging = FirebaseMessaging.instance;
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
    switch (settings.authorizationStatus) {
      case AuthorizationStatus.authorized:
        if (kIsWeb) {
          return messaging.getToken(
              vapidKey:
                  'Key');
        } else {
          return messaging.getToken();
        }
      case AuthorizationStatus.denied:
        return null;
      case AuthorizationStatus.notDetermined:
        return null;
      case AuthorizationStatus.provisional:
        return messaging.getToken();
    }
  }

Firebase Core version

3.1.1

Flutter Version

3.19.3

Relevant Log Output

Error
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 330:10  createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 337:28            _throw
dart-sdk/lib/core/errors.dart 120:5                                           throwWithStackTrace
dart-sdk/lib/async/zone.dart 1386:11                                          callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7            <fn>

Flutter dependencies

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

Additional context and comments

Doctor summary (to see all details, run flutter doctor -v): [βœ“] Flutter (Channel stable, 3.19.3, on macOS 14.4.1 23E224 darwin-arm64, locale pl-PL) [βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.0) [βœ“] Xcode - develop for iOS and macOS (Xcode 15.4) [βœ“] Chrome - develop for the web [βœ“] Android Studio (version 2023.2) [βœ“] VS Code (version 1.90.2) [βœ“] Connected device (3 available) [βœ“] Network resources

β€’ No issues found!

TarekkMA commented 3 days ago

@mklepaczko Thank you for reporting this issue. I've run the FlutterFire messaging example app found here. The getToken(vapidKey: ...) works without issue. Can you share a minimal reproducible example app where this issue occurs?

Also, please try using the latest Flutter version and the latest firebase_messaging version.

mklepaczko commented 3 days ago

Hi, thanks for your answer.

i just updated to Flutter 3.22.2 but still the same.

Here is a sample app configured with firebase:

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_web_frame/flutter_web_frame.dart';
import 'package:projekty_dev/firebase_options.dart';

void main() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return FlutterWebFrame(
      builder: (context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            // This is the theme of your application.
            //
            // TRY THIS: Try running your application with "flutter run". You'll see
            // the application has a blue toolbar. Then, without quitting the app,
            // try changing the seedColor in the colorScheme below to Colors.green
            // and then invoke "hot reload" (save your changes or press the "hot
            // reload" button in a Flutter-supported IDE, or press "r" if you used
            // the command line to start the app).
            //
            // Notice that the counter didn't reset back to zero; the application
            // state is not lost during the reload. To reset the state, use hot
            // restart instead.
            //
            // This works for code too, not just values: Most code changes can be
            // tested with just a hot reload.
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      },
      maximumSize: const Size(800, 800),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  Future messagingPermissions() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      debugPrint('User granted permission');
      FirebaseMessaging.instance.getToken(
        vapidKey:
            'BKE0htV7ksYElGdkn9Xi-eCchkhnsWJceIOeuQkI2qK7M7fq4HivEZ7opk-2-4VqVHC0SBY_GDedAAGfjiWilqs');
    } else {
      debugPrint('User declined or has not yet granted permission');
    }

  }

  @override
  Widget build(BuildContext context) {
    messagingPermissions();
    final double width = MediaQuery.of(context).size.width;
    final double height = MediaQuery.of(context).size.height;
    debugPrint('Screen is of $height height and $width width');
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.

    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

The error comes in this file /firebase_messaging_web-3.8.10/lib/src/interop/messaging.dart

Future<String> getToken({String? vapidKey}) async {
    try {
      final token = ((await messaging_interop
              .getToken(
                  jsObject,
                  vapidKey == null
                      ? null
                      : messaging_interop.GetTokenOptions(
                          vapidKey: vapidKey.toJS))
              .toDart)! as JSString) // here the error is highlited
          .toDart;
      return token;
    } catch (err) {
      // A race condition can happen in which the service worker get registered
      // only when getToken is called. In this case, the first call to getToken
      // might fail.
      if (err.toString().toLowerCase().contains('no active service worker') &&
          firstGetTokenCall) {
        firstGetTokenCall = false;
        return getToken(vapidKey: vapidKey);
      }
      rethrow;
    }
  }
TarekkMA commented 3 days ago

I've replicated the code here: https://github.com/firebase/flutterfire/tree/issue/13010 and it works without issues. One possible cause for your issue could be an incorrect vapidKey. Can you check if you have the correct key?

mklepaczko commented 3 days ago

Ok I'm confused now and don't know where to look for the bug

It's ot an app code problem as it works with you

I create a new Vapid key to be sure, same problem

I connected the app to a different Firestore project and created a new key, same problem.

i created a new project and new VapidKey, same problem

What can I do next? any JS packages or similar to update? I just updated Flutter to the last version.

As for information getToken() works fine on IOS.

TarekkMA commented 3 days ago

@mklepaczko Can you try to run the example app from the linked branch and see if it's also causing issues? Additionally, could you try surrounding the erroring code with a try-catch block and print the error?

mklepaczko commented 3 days ago

Will try that. The error is above in the "Relevant log output"