Tracking Script

Integrate with Your Website

To start tracking real-time users on your website, copy the script below and paste it into the <head> section of your site's HTML.
<!-- AnalyticaLive Tracking Script -->
<script src="https://www.gstatic.com/firebasejs/10.12.2/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore-compat.js"></script>
<script>
  (function() {
    const firebaseConfig = {
  "projectId": "studio-2454641399-6aae1",
  "appId": "1:72994632860:web:271d89eb207f19b5232959",
  "apiKey": "AIzaSyBd10jzmCJrvQffKnQIj6Xir8r8IZJqwKI",
  "authDomain": "studio-2454641399-6aae1.firebaseapp.com",
  "measurementId": "",
  "messagingSenderId": "72994632860"
};

    // Use a unique name to avoid conflicts if host page uses Firebase
    const analyticaApp = firebase.initializeApp(firebaseConfig, 'analyticaLive');
    const firestore = analyticaApp.firestore();

    let sessionId = sessionStorage.getItem('analytica_session_id');
    if (!sessionId) {
      sessionId = Date.now().toString(36) + Math.random().toString(36).substring(2);
      sessionStorage.setItem('analytica_session_id', sessionId);
    }

    const trackEvent = (eventType) => {
      const url = new URL(window.location.href);
      const utmParams = new URLSearchParams(url.search);

      const eventData = {
        websiteId: 'default-website', // This should be dynamic in a real multi-tenant app
        sessionId: sessionId,
        timestamp: new Date(),
        eventType: eventType,
        pagePath: url.pathname,
        referrer: document.referrer,
        utmSource: utmParams.get('utm_source') || null,
        utmMedium: utmParams.get('utm_medium') || null,
        userAgent: navigator.userAgent,
        // countryCode and ipAddress are omitted, to be added on the backend if possible
      };

      firestore.collection('websites/default-website/websiteEvents').add(eventData)
        .catch(err => console.error('AnalyticaLive Error: ', err));
    };

    // Track initial page view
    trackEvent('page_view');

    // Send a heartbeat every 30 seconds to keep the session active
    const heartbeatInterval = setInterval(() => trackEvent('heartbeat'), 30000);
    
    // Clean up interval on page unload
    window.addEventListener('beforeunload', () => {
        clearInterval(heartbeatInterval);
    });

  })();
</script>