FirebaseAnalytics.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // FirebaseAnalytics.js
  2. let firebaseAnalyticsInstance = null;
  3. class FirebaseAnalytics {
  4. /**
  5. * @param {Object} config
  6. * @param {string} config.measurementId - Measurement ID (例如:G-XXXXXXXXXX)
  7. * @param {string} config.apiSecret - API Secret
  8. * @param {string} config.firebaseAppId - Firebase App ID
  9. * @param {string} config.clientId - 客户端ID,通常来自客户端 cookie 或设备唯一标识
  10. */
  11. constructor({ measurementId, apiSecret, firebaseAppId, clientId }) {
  12. this.measurementId = measurementId;
  13. this.apiSecret = apiSecret;
  14. this.firebaseAppId = firebaseAppId;
  15. this.clientId = clientId;
  16. // 构造上报的 URL,参考 Measurement Protocol 规范
  17. this.endpoint = `https://www.google-analytics.com/mp/collect?firebase_app_id=${this.firebaseAppId}&api_secret=${this.apiSecret}`;
  18. }
  19. /**
  20. * 上报事件到 Firebase Analytics
  21. * @param {string} eventName - 事件名称,例如 "user_sign_in"
  22. * @param {Object} params - 事件参数(键值对),例如 { page: 'home', duration: 123 }
  23. * @returns {Promise<Response>} 返回 fetch 的响应结果
  24. */
  25. async sendEvent(eventName, params = {}) {
  26. // 构造 Measurement Protocol 所要求的 payload
  27. const payload = {
  28. app_instance_id: this.clientId,
  29. events: [
  30. {
  31. name: eventName,
  32. params: params
  33. }
  34. ]
  35. };
  36. try {
  37. const response = await fetch(this.endpoint, {
  38. method: 'POST',
  39. headers: {
  40. 'Content-Type': 'application/json'
  41. },
  42. body: JSON.stringify(payload)
  43. });
  44. if (!response.ok) {
  45. throw new Error(`事件上报失败,状态码:${response.status}`);
  46. }
  47. return response;
  48. } catch (error) {
  49. console.error('FirebaseAnalytics 上报错误:', error);
  50. throw error;
  51. }
  52. }
  53. }
  54. // Initialize Firebase Analytics
  55. const initializeFirebaseAnalytics = (measurementId, apiSecret, firebaseAppId='',clientId='') => {
  56. if (!firebaseAnalyticsInstance) {
  57. firebaseAnalyticsInstance = new FirebaseAnalytics({measurementId, apiSecret, firebaseAppId,clientId});
  58. console.log('Firebase Analytics initialized');
  59. } else {
  60. console.warn('Firebase Analytics is already initialized');
  61. }
  62. };
  63. // Interface function for external calls
  64. const fa_trackEvent = (eventName, eventParams) => {
  65. if (!firebaseAnalyticsInstance) {
  66. console.error('Firebase Analytics is not initialized. Please call initializeFirebaseAnalytics first.');
  67. return;
  68. }
  69. firebaseAnalyticsInstance.sendEvent(eventName, eventParams);
  70. };
  71. // Example usage
  72. // initializeFirebaseAnalytics('YOUR_MEASUREMENT_ID', 'YOUR_API_SECRET', 'YOUR_FIREBASE_APP_ID');
  73. // fa_trackEvent('example_event', { param1: 'value1', param2: 'value2' });
  74. export { initializeFirebaseAnalytics, fa_trackEvent };