1
0
mirror of https://github.com/kremalicious/gatsby-plugin-matomo.git synced 2024-12-23 01:29:42 +01:00
gatsby-plugin-matomo/src/gatsby-browser.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-05-07 18:29:27 +02:00
let first = true
function getDuration() {
const start = window.start || new Date()
const now = new Date()
const difference = now.getTime() - start.getTime()
if (difference === 0) {
return null
}
return difference
}
2020-04-04 17:30:35 +02:00
export const onRouteUpdate = ({ location, prevLocation }, pluginOptions) => {
2020-02-15 15:21:24 +01:00
if (process.env.NODE_ENV === 'production' || window.dev === true) {
if (!window._paq) return
2020-02-15 15:21:24 +01:00
const { _paq, dev } = window
const url = location && location.pathname + location.search + location.hash
2019-06-10 02:04:28 +02:00
const prevUrl =
prevLocation &&
prevLocation.pathname + prevLocation.search + prevLocation.hash
2018-05-07 18:29:27 +02:00
2020-04-06 10:55:51 +02:00
const { trackLoad = true } = pluginOptions
2020-04-04 17:30:35 +02:00
// document.title workaround stolen from:
// https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-plugin-google-analytics/src/gatsby-browser.js
const sendPageView = () => {
const { title } = document
prevUrl && _paq.push(['setReferrerUrl', prevUrl])
_paq.push(['setCustomUrl', url])
_paq.push(['setDocumentTitle', title])
_paq.push(['trackPageView'])
_paq.push(['enableLinkTracking'])
_paq.push(['trackAllContentImpressions'])
if (dev) {
2020-02-15 14:07:20 +01:00
console.debug(`[Matomo] Page view for: ${url} - ${title}`)
}
}
2020-02-15 15:21:24 +01:00
// Minimum delay for reactHelmet's requestAnimationFrame
const delay = Math.max(32, 0)
setTimeout(sendPageView, delay)
if (first) {
first = false
2020-04-04 17:30:35 +02:00
if (trackLoad) {
2020-04-06 10:55:51 +02:00
_paq.push([
'trackEvent',
'javascript',
'load',
'duration',
getDuration()
])
2020-04-04 17:30:35 +02:00
}
if (dev) {
2020-02-15 14:07:20 +01:00
console.debug(`[Matomo] Tracking duration for: ${url}`)
}
}
2018-05-07 18:29:27 +02:00
}
2020-02-15 14:07:20 +01:00
return null
2018-05-07 18:29:27 +02:00
}