Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Merge pull request #143 from Amsterdam/feature/ssr-support
Browse files Browse the repository at this point in the history
Check if there is a valid window object when initializing matomo
  • Loading branch information
royderks authored May 8, 2020
2 parents 01a1279 + 66f79e6 commit 57867b7
Showing 1 changed file with 32 additions and 27 deletions.
59 changes: 32 additions & 27 deletions packages/js/src/MatomoTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,32 +31,37 @@ class MatomoTracker {
urlBase = urlBase + '/'
}

window._paq = window._paq || []

if (window._paq.length === 0) {
window._paq.push(['setTrackerUrl', trackerUrl || `${urlBase}matomo.php`])
window._paq.push(['setSiteId', siteId])

// accurately measure the time spent on the last pageview of a visit
if (!heartBeat || (heartBeat && heartBeat.active)) {
this.enableHeartBeatTimer(15 || (heartBeat && heartBeat.seconds))
}

// // measure outbound links and downloads
// // might not work accurately on SPAs because new links (dom elements) are created dynamically without a server-side page reload.
this.enableLinkTracking(true)

const doc = document
const scriptElement = doc.createElement('script')
const scripts = doc.getElementsByTagName('script')[0]

scriptElement.type = 'text/javascript'
scriptElement.async = true
scriptElement.defer = true
scriptElement.src = srcUrl || `${urlBase}matomo.js`

if (scripts && scripts.parentNode) {
scripts.parentNode.insertBefore(scriptElement, scripts)
if (typeof window !== 'undefined') {
window._paq = window._paq || []

if (window._paq.length === 0) {
window._paq.push([
'setTrackerUrl',
trackerUrl || `${urlBase}matomo.php`,
])
window._paq.push(['setSiteId', siteId])

// accurately measure the time spent on the last pageview of a visit
if (!heartBeat || (heartBeat && heartBeat.active)) {
this.enableHeartBeatTimer(15 || (heartBeat && heartBeat.seconds))
}

// // measure outbound links and downloads
// // might not work accurately on SPAs because new links (dom elements) are created dynamically without a server-side page reload.
this.enableLinkTracking(true)

const doc = document
const scriptElement = doc.createElement('script')
const scripts = doc.getElementsByTagName('script')[0]

scriptElement.type = 'text/javascript'
scriptElement.async = true
scriptElement.defer = true
scriptElement.src = srcUrl || `${urlBase}matomo.js`

if (scripts && scripts.parentNode) {
scripts.parentNode.insertBefore(scriptElement, scripts)
}
}
}
}
Expand All @@ -75,7 +80,7 @@ class MatomoTracker {
document.querySelectorAll<HTMLElement>('[data-matomo-event="click"]'),
)
if (elements.length) {
elements.forEach((element) => {
elements.forEach(element => {
element.addEventListener('click', () => {
const {
matomoCategory,
Expand Down

0 comments on commit 57867b7

Please sign in to comment.