gatsby-plugin-matomo/src/gatsby-browser.js

66 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-02-15 14:07:20 +01:00
export const onRouteUpdate = ({ location, prevLocation }) => {
2019-06-10 02:04:28 +02:00
if (
(process.env.NODE_ENV === 'production' && typeof _paq !== 'undefined') ||
window.dev === true
) {
const _paq = window._paq || []
const dev = window.dev || null
const url = 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
// 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}`)
}
}
if ('requestAnimationFrame' in window) {
requestAnimationFrame(() => {
requestAnimationFrame(sendPageView)
})
} else {
// simulate 2 rAF calls
setTimeout(sendPageView, 32)
}
if (first) {
first = false
2019-06-10 02:04:28 +02:00
_paq.push(['trackEvent', 'javascript', 'load', 'duration', getDuration()])
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
}