Skip to content

Uncaught FirebaseError: Analytics: Cookies are not enabled in this browser environment #3749

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

Closed
salek-zylk opened this issue Sep 9, 2020 · 8 comments

Comments

@salek-zylk
Copy link

[REQUIRED] Describe your environment

  • Operating System version: Ubuntu 20.04
  • Browser version: 85.0.4183.83
  • Firebase SDK version: 7.19.0
  • Firebase Product: analytics

[REQUIRED] Describe the problem

I am integrating an app of react with firebase (notifications and analytics) but analytics dont work. The browser is Chrome and the cookis are enabled

Steps to reproduce:

The console error is this:
provider.ts:108 Uncaught FirebaseError: Analytics: Cookies are not enabled in this browser environment. Analytics requires cookies to be enabled. (analytics/cookies-not-enabled).
at rt (https://www.gstatic.com/firebasejs/7.19.0/firebase-analytics.js:1:25586)
at _.instanceFactory (https://www.gstatic.com/firebasejs/7.19.0/firebase-analytics.js:1:27688)
at S.getOrInitializeService (https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js:1:8327)
at S.getImmediate (https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js:1:6591)
at q._getService (https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js:1:13984)
at q.analytics (https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js:1:17384)

Relevant Code:

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
@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.

@hsubox76
Copy link
Contributor

hsubox76 commented Sep 9, 2020

In your app code, before initializing Firebase, can you console log the value of navigator.cookieEnabled? Is it true? If not, can you think of anything in your environment that might cause it to be false? An ad blocker?

This error should only occur if navigator.cookieEnabled is false (or falsy) in your environment.

@salek-zylk
Copy link
Author

salek-zylk commented Sep 9, 2020

Thank you @hsubox76.
I printed the value of navigator.cookieEnabled and it is "undefined". I test in Chrome of Linux and in Chrome of Windows. I haven't got adblocks.

This is the snippet of firebase-messaging-sw.js. Maybe need it more importScripts?

/* eslint-disable no-undef */
// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.19.1/firebase-messaging.js');
importScripts('https://www.gstatic.com/firebasejs/7.19.1/firebase-analytics.js');

var firebaseConfig = {
  apiKey: "kk",
  authDomain: "kk",
  databaseURL: "kk",
  projectId: "kk",
  storageBucket: "kk",
  messagingSenderId: "kk",
  appId: "kk",
  measurementId: "G-kk"
};

// Initialize Firebase
console.log('navigator.cookieEnabled: ' + navigator.cookieEnabled);
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
// eslint-disable-next-line no-restricted-globals
self.addEventListener('notificationclick', function(event) {
	console.log("antes de cerrar");
  event.notification.close();
  console.log("después de cerrar");
  event.waitUntil(
    clients.openWindow(event.notification.data.url)
  );
  
}
, false);

// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
	console.log("antes de mostrar");
  const notification = payload.notification ? payload.notification : payload.data.message ? JSON.parse(payload.data.message).notification : payload.data.payload ? JSON.parse(payload.data.payload).notification : JSON.parse(payload);
  const notificationTitle = notification.title || 'Background Message Title';
  const notificationOptions = {
    body: notification.body || 'Background Message body.',
    icon: '/new-logo192.png',
    data: { url: notification.url }
  };

  // eslint-disable-next-line no-restricted-globals
  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});
// [END background_handler]```

@salek-zylk
Copy link
Author

Other test has printed the object navigator. The result is:
firebase-messaging-sw.js:21 navigator: [object WorkerNavigator]

The documentation of WorkerNavigator says:
The WorkerNavigator interface represents a subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator.

@hsubox76
Copy link
Contributor

hsubox76 commented Sep 9, 2020

Cookies aren't available in service workers, and Analytics requires cookies to work. Is there a reason you're trying to import analytics in the service worker instead of in regular client code?

If so, unfortunately, Firebase Analytics won't work in this environment. If you need it to do something in response to notifications you may have to have the service worker send a message to the standard browser runtime, and do analytics stuff there.

@salek-zylk
Copy link
Author

Its important register event in service worker because i need register the event of background notifications:

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
	console.log("antes de mostrar");
  const notification = payload.notification ? payload.notification : payload.data.message ? JSON.parse(payload.data.message).notification : payload.data.payload ? JSON.parse(payload.data.payload).notification : JSON.parse(payload);
  const notificationTitle = notification.title || 'Background Message Title';
  const notificationOptions = {
    body: notification.body || 'Background Message body.',
    icon: '/new-logo192.png',
    data: { url: notification.url }
  };

and when the user click notifications

// eslint-disable-next-line no-restricted-globals
self.addEventListener('notificationclick', function(event) {
	console.log("antes de cerrar");
  event.notification.close();
  console.log("después de cerrar");
  event.waitUntil(
    clients.openWindow(event.notification.data.url)
  );
  
}
, false);

Actually, in client NotificationPush.tsx work correctly for foreground notifications.

    showMessage = (payload: any) => {
        const notification = payload.notification ? payload.notification : payload.data.message ? JSON.parse(payload.data.message).notification : payload.data.payload ? JSON.parse(payload.data.payload).notification : JSON.parse(payload);
        const notificationTitle = notification.title || 'Foreground Message Title';
        const notificationBody = notification.body || 'Foreground Message body.';
        console.log("zk: showMessage");
		firebase.analytics().logEvent('notification_received');
        this.setState({
            title: notificationTitle,
            body: notificationBody,
            showMessage: true
        });

Do you know an alternative to manage notifications background from client instead of service worker ?

@hsubox76
Copy link
Contributor

hsubox76 commented Sep 9, 2020

I think there are a number of ways to communicate between service workers and the window context? https://felixgerschau.com/how-to-communicate-with-service-workers/#service-worker---client-communication

But I think this is out of scope for a Firebase JS SDK issue. There doesn't seem to be a bug, and Analytics will not work in a service worker context and this can't be changed in the near future (see #2243 (comment)). For workarounds or solutions for your specific issue, maybe search around or try Stack Overflow.

@salek-zylk
Copy link
Author

Thank you very much @hsubox76 . it has helped me a lot.
I have revised google lab and find an example perfect for me:
https://codelabs.developers.google.com/codelabs/pwa-integrating-analytics/index.html

And here example code:
https://github.com/gauntface/simple-push-demo

@firebase firebase locked and limited conversation to collaborators Oct 11, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants