Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Add tagged-events script extension (#2333)

RobertJoonas135471c32e1f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7bbf55c08..d6ce06a3d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file.
## Unreleased
### Added
+- A `tagged-events` script extension for out-of-the-box custom event tracking
- The ability to escape `|` characters with `\` in Stats API filter values
- An upper bound of 1000 to the `limit` parameter in Stats API
- The `exclusions` script extension now also takes a `data-include` attribute tag
diff --git a/lib/plausible_web/plugs/tracker.ex b/lib/plausible_web/plugs/tracker.ex
index b11dc4f7a7..cd10a955f4 100644
--- a/lib/plausible_web/plugs/tracker.ex
+++ b/lib/plausible_web/plugs/tracker.ex
@@ -10,7 +10,8 @@ defmodule PlausibleWeb.Tracker do
"local",
"manual",
"file-downloads",
- "dimensions"
+ "dimensions",
+ "tagged-events"
]
# Generates Power Set of all variants
diff --git a/tracker/compile.js b/tracker/compile.js
index 2da88662d6..125cc835a5 100644
--- a/tracker/compile.js
+++ b/tracker/compile.js
@@ -8,6 +8,8 @@ Handlebars.registerHelper('any', function (...args) {
return args.slice(0, -1).some(Boolean)
})
+Handlebars.registerPartial('customEvents', Handlebars.compile(fs.readFileSync(relPath('src/customEvents.js')).toString()))
+
function relPath(segment) {
return path.join(__dirname, segment)
}
@@ -24,7 +26,7 @@ function compilefile(input, output, templateVars = {}) {
}
}
-const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "dimensions"]
+const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "dimensions", "tagged-events"]
const variants = [...g.clone.powerSet(base_variants)].filter(a => a.length > 0).map(a => a.sort());
compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.js'))
diff --git a/tracker/src/customEvents.js b/tracker/src/customEvents.js
new file mode 100644
index 0000000000..7d3c563aa8
--- /dev/null
+++ b/tracker/src/customEvents.js
@@ -0,0 +1,198 @@
+function getLinkEl(link) {
+ while (link && (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)) {
+ link = link.parentNode
+ }
+ return link
+}
+
+function isLink(element) {
+ return element && element.tagName && element.tagName.toLowerCase() === 'a'
+}
+
+function shouldFollowLink(event, link) {
+ // If default has been prevented by an external script, Plausible should not intercept navigation.
+ if (event.defaultPrevented) { return false }
+
+ var targetsCurrentWindow = !link.target || link.target.match(/^_(self|parent|top)$/i)
+ var isRegularClick = !(event.ctrlKey || event.metaKey || event.shiftKey) && event.type === 'click'
+ return targetsCurrentWindow && isRegularClick
+}
+
+var MIDDLE_MOUSE_BUTTON = 1
+
+function handleLinkClickEvent(event) {
+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
+
+ var link = getLinkEl(event.target)
+ var hrefWithoutQuery = link && link.href && link.href.split('?')[0]
+
+ {{#if tagged_events}}
+ if (isElementOrParentTagged(link, 0)) {
+ // Return to prevent sending multiple events with the same action.
+ // Clicks on tagged links are handled by another function.
+ return
+ }
+ {{/if}}
+
+ {{#if outbound_links}}
+ if (isOutboundLink(link)) {
+ return sendLinkClickEvent(event, link, { name: 'Outbound Link: Click', props: { url: link.href } })
+ }
+ {{/if}}
+
+ {{#if file_downloads}}
+ if (isDownloadToTrack(hrefWithoutQuery)) {
+ return sendLinkClickEvent(event, link, { name: 'File Download', props: { url: hrefWithoutQuery } })
+ }
+ {{/if}}
+}
+
+function sendLinkClickEvent(event, link, eventAttrs) {
+ var followedLink = false
+
+ function followLink() {
+ if (!followedLink) {
+ followedLink = true
+ window.location = link.href
+ }
+ }
+
+ if (shouldFollowLink(event, link)) {
+ plausible(eventAttrs.name, { props: eventAttrs.props, callback: followLink })
+ setTimeout(followLink, 5000)
+ event.preventDefault()
+ } else {
+ plausible(eventAttrs.name, { props: eventAttrs.props })
+ }
+}
+
+document.addEventListener('click', handleLinkClickEvent)
+document.addEventListener('auxclick', handleLinkClickEvent)
+
+{{#if outbound_links}}
+function isOutboundLink(link) {
+ return link && link.href && link.host && link.host !== location.host
+}
+{{/if}}
+
+{{#if file_downloads}}
+var defaultFileTypes = ['pdf', 'xlsx', 'docx', 'txt', 'rtf', 'csv', 'exe', 'key', 'pps', 'ppt', 'pptx', '7z', 'pkg', 'rar', 'gz', 'zip', 'avi', 'mov', 'mp4', 'mpeg', 'wmv', 'midi', 'mp3', 'wav', 'wma']
+var fileTypesAttr = scriptEl.getAttribute('file-types')
+var addFileTypesAttr = scriptEl.getAttribute('add-file-types')
+var fileTypesToTrack = (fileTypesAttr && fileTypesAttr.split(",")) || (addFileTypesAttr && addFileTypesAttr.split(",").concat(defaultFileTypes)) || defaultFileTypes;
+
+function isDownloadToTrack(url) {
+ if (!url) { return false }
+
+ var fileType = url.split('.').pop();
+ return fileTypesToTrack.some(function (fileTypeToTrack) {
+ return fileTypeToTrack === fileType
+ })
+}
+{{/if}}
+
+{{#if tagged_events}}
+// Finds event attributes by iterating over the given element's (or its
+// parent's) classList. Returns an object with `name` and `props` keys.
+function getTaggedEventAttributes(htmlElement) {
+ var taggedElement = isTagged(htmlElement) ? htmlElement : htmlElement && htmlElement.parentNode
+ var eventAttrs = { name: null, props: {} }
+
+ var classList = taggedElement && taggedElement.classList
+ if (!classList) { return eventAttrs }
+
+ for (var i = 0; i < classList.length; i++) {
+ var className = classList.item(i)
+
+ var matchList = className.match(/plausible-event-(.+)=(.+)/)
+ if (!matchList) { continue }
+
+ var key = matchList[1]
+ var value = matchList[2].replace(/\+/g, ' ')
+
+ if (key.toLowerCase() === 'name') {
+ eventAttrs.name = value
+ } else {
+ eventAttrs.props[key] = value
+ }
+ }
+
+ return eventAttrs
+}
+
+function handleTaggedFormSubmitEvent(event) {
+ var form = event.target
+ var eventAttrs = getTaggedEventAttributes(form)
+ if (!eventAttrs.name) { return }
+
+ event.preventDefault()
+ var formSubmitted = false
+
+ function submitForm() {
+ if (!formSubmitted) {
+ formSubmitted = true
+ form.submit()
+ }
+ }
+
+ setTimeout(submitForm, 5000)
+ plausible(eventAttrs.name, { props: eventAttrs.props, callback: submitForm })
+}
+
+function isForm(element) {
+ return element && element.tagName && element.tagName.toLowerCase() === 'form'
+}
+
+var PARENTS_TO_SEARCH_LIMIT = 3
+
+function handleTaggedElementClickEvent(event) {
+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
+
+ var clicked = event.target
+
+ var clickedLink
+ var taggedElement
+ // Iterate over parents to find the tagged element. Also search for
+ // a link element to call for different tracking behavior if found.
+ for (var i = 0; i <= PARENTS_TO_SEARCH_LIMIT; i++) {
+ if (!clicked) { break }
+
+ // Clicks inside forms are not tracked. Only form submits are.
+ if (isForm(clicked)) { return }
+ if (isLink(clicked)) { clickedLink = clicked }
+ if (isTagged(clicked)) { taggedElement = clicked }
+ clicked = clicked.parentNode
+ }
+
+ if (taggedElement) {
+ var eventAttrs = getTaggedEventAttributes(taggedElement)
+
+ if (clickedLink) {
+ eventAttrs.props.url = clickedLink.href
+ sendLinkClickEvent(event, clickedLink, eventAttrs)
+ } else {
+ plausible(eventAttrs.name, { props: eventAttrs.props })
+ }
+ }
+}
+
+function isTagged(element) {
+ var classList = element && element.classList
+ if (classList) {
+ for (var i = 0; i < classList.length; i++) {
+ if (classList.item(i).match(/plausible-event-name=(.+)/)) { return true }
+ }
+ }
+ return false
+}
+
+function isElementOrParentTagged(element, parentsChecked) {
+ if (!element || parentsChecked > PARENTS_TO_SEARCH_LIMIT) { return false }
+ if (isTagged(element)) { return true }
+ return isElementOrParentTagged(element.parentNode, parentsChecked + 1)
+}
+
+document.addEventListener('submit', handleTaggedFormSubmitEvent)
+document.addEventListener('click', handleTaggedElementClickEvent)
+document.addEventListener('auxclick', handleTaggedElementClickEvent)
+{{/if}}
diff --git a/tracker/src/plausible.js b/tracker/src/plausible.js
index 10f14b2fd5..6aa6d2e628 100644
--- a/tracker/src/plausible.js
+++ b/tracker/src/plausible.js
@@ -155,91 +155,7 @@
}
{{/unless}}
- // CUSTOM EVENT TRACKING
- {{#if (any outbound_links file_downloads)}}
- function getLinkEl(link) {
- while (link && (typeof link.tagName === 'undefined' || link.tagName.toLowerCase() !== 'a' || !link.href)) {
- link = link.parentNode
- }
- return link
- }
-
- function shouldFollowLink(event, link) {
- // If default has been prevented by an external script, Plausible should not intercept navigation.
- if (event.defaultPrevented) { return false }
-
- var targetsCurrentWindow = !link.target || link.target.match(/^_(self|parent|top)$/i)
- var isRegularClick = !(event.ctrlKey || event.metaKey || event.shiftKey) && event.type === 'click'
- return targetsCurrentWindow && isRegularClick
- }
-
- var MIDDLE_MOUSE_BUTTON = 1
-
- function handleLinkClickEvent(event) {
- if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
-
- var link = getLinkEl(event.target)
- var hrefWithoutQuery = link && link.href && link.href.split('?')[0]
-
- {{#if outbound_links}}
- if (isOutboundLink(link)) {
- var eventName = 'Outbound Link: Click'
- var eventProps = {url: link.href}
- return sendLinkClickEvent(event, link, eventName, eventProps)
- }
- {{/if}}
-
- {{#if file_downloads}}
- if (isDownloadToTrack(hrefWithoutQuery)) {
- var eventName = 'File Download'
- var eventProps = {url: hrefWithoutQuery}
- return sendLinkClickEvent(event, link, eventName, eventProps)
- }
- {{/if}}
- }
-
- function sendLinkClickEvent(event, link, eventName, eventProps) {
- var followedLink = false
-
- function followLink() {
- if (!followedLink) {
- followedLink = true
- window.location = link.href
- }
- }
-
- if (shouldFollowLink(event, link)) {
- plausible(eventName, { props: eventProps, callback: followLink })
- setTimeout(followLink, 5000)
- event.preventDefault()
- } else {
- plausible(eventName, { props: eventProps })
- }
- }
-
- document.addEventListener('click', handleLinkClickEvent)
- document.addEventListener('auxclick', handleLinkClickEvent)
- {{/if}}
-
- {{#if outbound_links}}
- function isOutboundLink(link) {
- return link && link.href && link.host && link.host !== location.host
- }
- {{/if}}
-
- {{#if file_downloads}}
- var defaultFileTypes = ['pdf', 'xlsx', 'docx', 'txt', 'rtf', 'csv', 'exe', 'key', 'pps', 'ppt', 'pptx', '7z', 'pkg', 'rar', 'gz', 'zip', 'avi', 'mov', 'mp4', 'mpeg', 'wmv', 'midi', 'mp3', 'wav', 'wma']
- var fileTypesAttr = scriptEl.getAttribute('file-types')
- var addFileTypesAttr = scriptEl.getAttribute('add-file-types')
- var fileTypesToTrack = (fileTypesAttr && fileTypesAttr.split(",")) || (addFileTypesAttr && addFileTypesAttr.split(",").concat(defaultFileTypes)) || defaultFileTypes;
-
- function isDownloadToTrack(url) {
- if (!url) { return false }
-
- var fileType = url.split('.').pop();
- return fileTypesToTrack.some(function(fileTypeToTrack) {
- return fileTypeToTrack === fileType
- })
- }
+ {{#if (any outbound_links file_downloads tagged_events)}}
+ {{> customEvents}}
{{/if}}
})();
diff --git a/tracker/test/custom-event-edge-cases.spec.js b/tracker/test/custom-event-edge-cases.spec.js
index b9762fd549..d946fbca57 100644
--- a/tracker/test/custom-event-edge-cases.spec.js
+++ b/tracker/test/custom-event-edge-cases.spec.js
@@ -4,7 +4,7 @@ const { expect } = require('@playwright/test');
const { LOCAL_SERVER_ADDR } = require('./support/server');
-test.describe('script.file-downloads.outbound-links.js', () => {
+test.describe('script.file-downloads.outbound-links.tagged-events.js', () => {
test('sends only outbound link event when clicked link is both download and outbound', async ({ page }) => {
await page.goto('/custom-event-edge-case.html')
const downloadURL = await page.locator('#outbound-download-link').getAttribute('href')
@@ -26,4 +26,15 @@ test.describe('script.file-downloads.outbound-links.js', () => {
expectCustomEvent(await plausibleRequestMock, 'File Download', {url: downloadURL})
});
+
+ test('sends only tagged event when clicked link is tagged + outbound + download', async ({ page }) => {
+ await page.goto('/custom-event-edge-case.html')
+
+ const plausibleRequestMockList = mockManyRequests(page, '/api/event', 3)
+ await page.click('#tagged-outbound-download-link')
+
+ const requests = await plausibleRequestMockList
+ expect(requests.length).toBe(1)
+ expectCustomEvent(requests[0], 'Foo', {})
+ });
});
diff --git a/tracker/test/fixtures/custom-event-edge-case.html b/tracker/test/fixtures/custom-event-edge-case.html
index f5019dae74..0461ce87cd 100644
--- a/tracker/test/fixtures/custom-event-edge-case.html
+++ b/tracker/test/fixtures/custom-event-edge-case.html
@@ -7,13 +7,15 @@
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Plausible Playwright tests</title>
- <script defer src="/tracker/js/plausible.file-downloads.local.manual.outbound-links.js"></script>
+ <script defer src="/tracker/js/plausible.file-downloads.local.manual.outbound-links.tagged-events.js"></script>
</head>
<body>
<a id="outbound-download-link" href="https://awesome.website.com/file.pdf">Outbound Download</a>
<a id="local-download" href="file.csv">Local download</a>
+
+ <a id="tagged-outbound-download-link" class="plausible-event-name=Foo" href="https://awesome.website.com/file.pdf">Outbound Download</a>
</body>
</html>
diff --git a/tracker/test/fixtures/tagged-event.html b/tracker/test/fixtures/tagged-event.html
new file mode 100644
index 0000000000..c6b436e6b7
--- /dev/null
+++ b/tracker/test/fixtures/tagged-event.html
@@ -0,0 +1,80 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta http-equiv="X-UA-Compatible" content="ie=edge">
+ <title>Plausible Playwright tests</title>
+
+ <script defer src="/tracker/js/plausible.local.manual.tagged-events.js"></script>
+</head>
+
+<body>
+ <a id="link"
+ class="plausible-event-name=Payment+Complete should ignore-this plausible-event-amount=100 plausible-event-method=Credit+Card"
+ href="https://awesome.website.com/payment/">tagged link</a>
+
+ <form class="plausible-event-name=Signup plausible-event-type=Newsletter"
+ action="https://awesome.website.com/register" method="post">
+ <input type="text" id='form-text-input' />
+ <input id="form-submit" type="submit" value="Submit" />
+ </form>
+
+ <button id="button" class="plausible-event-name=Custom+Event plausible-event-foo=bar">
+ Button
+ </button>
+
+ <span id="span" class="plausible-event-name=Custom+Event plausible-event-foo=bar">
+ Span
+ </span>
+
+ <div id="div" class="plausible-event-name=Custom+Event plausible-event-foo=bar">
+ <a id="link-with-div-parent" href="https://awesome.website.com/payment/">Div child</a>
+ </div>
+
+ <a class="plausible-event-name=Custom+Event plausible-event-foo=bar" href="https://awesome.website.com/payment/">
+ <h2 id="h2-with-link-parent">Link child</h2>
+ </a>
+
+ <div class="plausible-event-name=Form+Submit">
+ <form action="https://awesome.website.com/register" method="post">
+ <input type="text" value="Form" />
+ <input id="submit-form-with-tagged-parent" type="submit" value="Submit" />
+ </form>
+ </div>
+
+ <a id="not-tracked-link" class="plausible-event-amount=100 plausible-event-method=Credit+Card"
+ href="https://awesome.website.com/payment/">
+ Link (without plausible-event-name class)
+ </a>
+
+ <button id="not-tracked-button" class="im not tracked">
+ Button (without plausible-event-name class)
+ </button>
+
+ <span id="not-tracked-span" class="plausible-event-name= still not tracked">
+ Span (without plausible-event-name class)
+ </span>
+
+
+ <script>
+ // Dynamically add a tagged element to DOM after one second
+ setTimeout(function () {
+ let taggedElement = document.createElement('button')
+ taggedElement.id = 'dynamic-tagged-button'
+ taggedElement.classList.add('plausible-event-name=Custom+Event')
+ taggedElement.innerHTML += 'Dynamic tagged button'
+ document.body.appendChild(taggedElement)
+ }, 1000)
+ </script>
+
+ <form id="form" class="plausible-event-name=Signup plausible-event-type=Newsletter"
+ action="https://awesome.website.com/register" method="post">
+ <input type="text" id='form-input' />
+ <div id="form-div">div in a form</div>
+ <input type="submit" value="Submit" />
+ </form>
+</body>
+
+</html>
diff --git a/tracker/test/tagged-events.spec.js b/tracker/test/tagged-events.spec.js
new file mode 100644
index 0000000000..04bd8e5ad5
--- /dev/null
+++ b/tracker/test/tagged-events.spec.js
@@ -0,0 +1,109 @@
+const { test } = require('./support/harness')
+const { mockRequest, mockManyRequests, isMac, expectCustomEvent } = require('./support/test-utils')
+const { expect } = require('@playwright/test')
+
+test.describe('tagged-events extension', () => {
+ test('tracks a tagged link click with custom props + url prop', async ({ page }) => {
+ await page.goto('/tagged-event.html')
+
+ const linkURL = await page.locator('#link').getAttribute('href')
+
+ const plausibleRequestMock = mockRequest(page, '/api/event')
+ await page.click('#link')
+ expectCustomEvent(await plausibleRequestMock, 'Payment Complete', { amount: '100', method: "Credit Card", url: linkURL })
+ });
+
+ test('tracks a tagged form submit with custom props when submitting by pressing enter', async ({ page }) => {
+ await page.goto('/tagged-event.html')
+ const plausibleRequestMock = mockRequest(page, '/api/event')
+
+ const inputLocator = page.locator('#form-text-input')
+ await inputLocator.type('some input')
+ await inputLocator.press('Enter')
+
+ expectCustomEvent(await plausibleRequestMock, 'Signup', { type: "Newsletter" })
+ });
+
+ test('tracks submit on a form with a tagged parent when submit button is clicked', async ({ page }) => {
+ await page.goto('/tagged-event.html')
+
+ const plausibleRequestMockList = mockManyRequests(page, '/api/event', 2)
+
+ await page.click('#submit-form-with-tagged-parent')
+
+ const requests = await plausibleRequestMockList
+
+ expect(requests.length).toBe(1)
+ expectCustomEvent(requests[0], "Form Submit", {})
+ });
+
+ test('tracks click and auxclick on any tagged HTML element', async ({ page }, workerInfo) => {
+ await page.goto('/tagged-event.html')
+
+ const plausibleRequestMockList = mockManyRequests(page, '/api/event', 3)
+
+ await page.click('#button')
+ await page.click('#span')
+ await page.click('#div', { modifiers: [isMac(workerInfo) ? 'Meta' : 'Control'] })
+
+ const requests = await plausibleRequestMockList
+ expect(requests.length).toBe(3)
+ requests.forEach(request => expectCustomEvent(request, 'Custom Event', { foo: "bar" }))
+ });
+
+ test('does not track elements without plausible-event-name class + link elements navigate', async ({ page }) => {
+ await page.goto('/tagged-event.html')
+ const linkLocator = page.locator('#not-tracked-link')
+
+ const linkURL = await linkLocator.getAttribute('href')
+
+ const plausibleRequestMock = mockRequest(page, '/api/event')
+ const navigationRequestMock = mockRequest(page, linkURL)
+
+ await page.click('#not-tracked-button')
+ await page.click('#not-tracked-span')
+ await linkLocator.click()
+
+ expect(await plausibleRequestMock, "should not have made Plausible request").toBeNull()
+ expect((await navigationRequestMock).url()).toContain(linkURL)
+ });
+
+ test('tracks tagged HTML elements when their child element is clicked', async ({ page }, workerInfo) => {
+ await page.goto('/tagged-event.html')
+
+ const plausibleRequestMockList = mockManyRequests(page, '/api/event', 2)
+
+ await page.click('#h2-with-link-parent', { modifiers: [isMac(workerInfo) ? 'Meta' : 'Control'] })
+ await page.click('#link-with-div-parent')
+
+ const requests = await plausibleRequestMockList
+ expect(requests.length).toBe(2)
+ requests.forEach(request => expectCustomEvent(request, 'Custom Event', { foo: "bar" }))
+ });
+
+ test('tracks tagged element that is dynamically added to the DOM', async ({ page }) => {
+ await page.goto('/tagged-event.html')
+
+ const plausibleRequestMock = mockRequest(page, '/api/event')
+
+ const buttonLocator = page.locator('#dynamic-tagged-button')
+ await buttonLocator.waitFor({state: 'visible'})
+ await page.waitForTimeout(500)
+
+ await buttonLocator.click()
+
+ expectCustomEvent(await plausibleRequestMock, 'Custom Event', {})
+ });
+
+ test('does not track clicks inside a tagged form, except submit click', async ({ page }) => {
+ await page.goto('/tagged-event.html')
+
+ const plausibleRequestMock = mockRequest(page, '/api/event')
+
+ await page.click('#form')
+ await page.click('#form-input')
+ await page.click('#form-div')
+
+ expect(await plausibleRequestMock, "should not have made Plausible request").toBeNull()
+ });
+});