Newer
Older
import { History, Location, UnregisterCallback } from 'history'
import { readCozyDataFromDOM } from 'cozy-ui/transpiled/react/helpers/appDataset'
interface InitSettings {
url: string
siteId: number
history: History
phpFilename?: string
}
declare global {
interface Window {
_paq: any
url: string
siteId: number
phpFilename: string
history: History
unlistenFromHistory: UnregisterCallback
constructor({
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.url = url
this.siteId = siteId
this.phpFilename = phpFilename
this.history = history
this.unlistenFromHistory = () => null
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(['enableLinkTracking'])
}
return {
push: MatomoTracker.push,
track: this.track,
connectToHistory: this.connectToHistory,
disconnectFromHistory: this.disconnectFromHistory,
}
}
static push(args: (number[] | string[] | number | string)[]) {
window._paq.push(args)
}
configure() {
let cozyDomain
let userId
const root: any = document.querySelector('[role=application]')
if (root && root.dataset) {
cozyDomain = readCozyDataFromDOM('cozyDomain')
}
if (cozyDomain) {
const indexOfPort = cozyDomain.indexOf(':')
if (indexOfPort >= 0) {
userId = userId.substring(0, indexOfPort)
}
}
}
connectToHistory() {
this.unlistenFromHistory = this.history.listen(loc => {
this.track(loc)
})
}
disconnectFromHistory() {
if (this.unlistenFromHistory) {
this.unlistenFromHistory()
return true
}
return false
}
track(loc: Location) {
if (typeof window === 'undefined') {
return
}
const currentPath = loc.hash.substring(1)
MatomoTracker.push(['setDocumentTitle', currentPath.substring(1)])
MatomoTracker.push(['setCustomUrl', 'https://ecolyo.com' + currentPath])
MatomoTracker.push(['trackPageView'])
}
}