Skip to content
Permalink
Browse files

capture and send custom page title

* workaround to delay page tracking until react-helmet is finished updating document.title
* closes #11
  • Loading branch information...
kremalicious committed Mar 30, 2019
1 parent 7b7f478 commit aedb80684fd485534e90d0f453ecd9efd688fa64
Showing with 30 additions and 17 deletions.
  1. +30 −15 src/gatsby-browser.js
  2. +0 −2 src/gatsby-ssr.js
@@ -16,34 +16,49 @@ function getDuration() {

exports.onRouteUpdate = ({ location, prevLocation }) => {
if (process.env.NODE_ENV === 'production' && typeof _paq !== 'undefined' || window.dev === true) {
window._paq = window._paq || []
window.dev = window.dev || null
const _paq = window._paq || []
const dev = window.dev || null

const url = location.pathname + location.search + location.hash
const prevUrl = prevLocation && prevLocation.pathname + prevLocation.search + prevLocation.hash

// 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'])

if (dev) {
console.log(`[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
window._paq.push([
_paq.push([
'trackEvent',
'javascript',
'load',
'duration',
getDuration()
])

if (window.dev) {
console.log(`[Matomo] Page view for: ${url}`)
}
} else {
window._paq.push(['setReferrerUrl', prevUrl])
window._paq.push(['setCustomUrl', url])
window._paq.push(['setDocumentTitle', url])
window._paq.push(['trackPageView'])
window._paq.push(['enableLinkTracking'])

if (window.dev) {
console.log(`[Matomo] Page view for: ${url}`)
if (dev) {
console.log(`[Matomo] Tracking duration for: ${url}`)
}
}
}
@@ -13,8 +13,6 @@ function buildTrackingCode(pluginOptions) {
${pluginOptions.disableCookies ? 'window._paq.push([\'disableCookies\']);' : ''}
window._paq.push(['setTrackerUrl', '${pluginOptions.matomoUrl}/piwik.php']);
window._paq.push(['setSiteId', '${pluginOptions.siteId}']);
window._paq.push(['trackPageView']);
window._paq.push(['enableLinkTracking']);
window._paq.push(['enableHeartBeatTimer']);
window.start = new Date();

0 comments on commit aedb806

Please sign in to comment.
You can’t perform that action at this time.