Skip to content
Snippets Groups Projects
matomoTracker.ts 1.83 KiB
Newer Older
  • Learn to ignore specific revisions
  • Bastien DUMONT's avatar
    Bastien DUMONT committed
    import { History } from 'history'
    import { Location } from 'react-router'
    
    
    interface InitSettings {
      cozyUrl: string
      url: string
      siteId: number
      history: History
      phpFilename?: string
    }
    
    declare global {
      interface Window {
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
        _paq: { push: (arg0: unknown) => void }
        Piwik: unknown
    
      }
    }
    
    export default class MatomoTracker {
      cozyUrl: string
      url: string
      siteId: number
      phpFilename: string
      history: History
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
      tracking = false
    
    
      constructor({
        cozyUrl,
        url,
        siteId,
        history,
        phpFilename = 'matomo.php',
      }: InitSettings) {
        if (url === undefined || siteId === undefined) {
          throw new Error(
            'MatomoTracker cannot be initialized! SiteId and url are mandatory.'
          )
        }
        this.cozyUrl = cozyUrl
        this.url = url
        this.siteId = siteId
        this.phpFilename = phpFilename
        this.history = history
        this.init()
      }
    
      init() {
        if (typeof window !== 'undefined') {
          window._paq = window._paq || []
          MatomoTracker.push(['enableHeartBeatTimer', 30])
          MatomoTracker.push(['setSiteId', this.siteId])
          MatomoTracker.push(['setReferrerUrl', 'https://ecolyo.com'])
          MatomoTracker.push(['setTrackerUrl', `${this.url + this.phpFilename}`])
    
          MatomoTracker.push(['HeatmapSessionRecording::disable'])
    
        }
        return {
          push: MatomoTracker.push,
          track: this.track,
        }
      }
    
      static push(args: (number[] | string[] | number | string)[]) {
        window._paq.push(args)
      }
    
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
      /** If matomo find a cookie "mtm_consent_removed" tracking will not be sent */
    
      track(loc: Location) {
        if (typeof window === 'undefined') {
          return
        }
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
        const currentPath = loc.pathname
    
    
        MatomoTracker.push(['setCustomUrl', 'https://ecolyo.com' + currentPath])
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
        MatomoTracker.push(['setDocumentTitle', currentPath.substring(1)])
    
        MatomoTracker.push(['trackPageView'])
      }
    }