首页 > 解决方案 > Google Firebase Analytics 实施

问题描述

尝试在 Firebase 托管网站(Firebase 项目的 WebApp)上实施 Google Analytics。

我尝试了 Firebase 建议的 SDK 片段:

自动的:

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="/__/firebase/7.16.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="/__/firebase/7.16.1/firebase-analytics.js"></script>

<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>

不执行跟踪,没有控制台错误。

CDN:

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js"></script>

<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "***************************************",
    authDomain: "test-project.firebaseapp.com",
    databaseURL: "https://test-project.firebaseio.com",
    projectId: "test-project",
    storageBucket: "test-project.appspot.com",
    messagingSenderId: "************",
    appId: "*:***************************************",
    measurementId: "G-**********"
    };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
</script> 

Chrome - 事件被跟踪,没有控制台错误;

FireFox - 事件未跟踪控制台错误:

Uncaught (in promise) DOMException: A mutation operation was attempted on a database that did not allow mutations.

Safari - 事件被跟踪,没有控制台错误;

Edge - 事件被跟踪,但是 - 控制台错误:

Tracking Prevention Blocked Access to storage for https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js.
Tracking Prevention Blocked Access to storage for https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js.

IE11 - 未跟踪事件,控制台错误:

Object doesn't support property or method 'value'

我做错了什么?

标签: javascriptfirebasegoogle-analyticscode-snippets

解决方案


在多次尝试使用“firebase.analytics()”使其工作失败后,我返回到使用“gaObjects”的“旧好”方法:

<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

然而,为了使其正常工作,鉴于 GA 最近宣布的新设置:“cookieFlags (analytics.js”),我通过添加“cookieFlags”修改了部分片段:

...
ga('create', 'UA-XXXXX-Y', {'cookieFlags': 'SameSite=None; Secure'});
...

现在它可以在所有浏览器中完美运行,没有错误,在“谷歌分析”中显示统计数据。当然 Firebase 分析控制台什么也没显示,但至少我可以在“Google Analytics”中查看使用 Firebase 托管的网站的统计信息


推荐阅读