Skip to content

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

ScriptV2: `plausible.init`, `customProperties`, snippet compilation, double initialization protection, `swc` (#5391)

Karl-Aksel Puulmann844c11813537
diff --git a/lib/plausible_web/tracker.ex b/lib/plausible_web/tracker.ex
index 037b00d692..e4e1cf94b7 100644
--- a/lib/plausible_web/tracker.ex
+++ b/lib/plausible_web/tracker.ex
@@ -25,7 +25,7 @@ defmodule PlausibleWeb.Tracker do
|> Enum.join(",")
@plausible_main_script
- |> String.replace("\"<%= @config_json %>\"", "{#{config_js_content}}")
+ |> String.replace("\"<%= @config_js %>\"", "{#{config_js_content}}")
end
def plausible_main_config(site) do
@@ -37,7 +37,6 @@ defmodule PlausibleWeb.Tracker do
hash: Map.get(script_config, "hash", false),
outboundLinks: Map.get(script_config, "outbound-links", false),
fileDownloads: Map.get(script_config, "file-downloads", false),
- pageviewProps: Map.get(script_config, "pageview-props", false),
taggedEvents: Map.get(script_config, "tagged-events", false),
revenue: Map.get(script_config, "revenue", false),
# Options not directly exposed via onboarding
diff --git a/test/plausible_web/tracker_test.exs b/test/plausible_web/tracker_test.exs
index 94d67f95fa..f135129c48 100644
--- a/test/plausible_web/tracker_test.exs
+++ b/test/plausible_web/tracker_test.exs
@@ -24,7 +24,6 @@ defmodule PlausibleWeb.TrackerTest do
hash: true,
outboundLinks: false,
fileDownloads: false,
- pageviewProps: false,
taggedEvents: true,
revenue: false,
local: false,
diff --git a/tracker/compile.js b/tracker/compile.js
index b24085f4cc..34aaf9eae7 100644
--- a/tracker/compile.js
+++ b/tracker/compile.js
@@ -1,5 +1,5 @@
import { parseArgs } from 'node:util'
-import { compileAll } from './compiler/index.js'
+import { compileAll, compileWebSnippet } from './compiler/index.js'
import chokidar from 'chokidar'
const { values, positionals } = parseArgs({
@@ -17,6 +17,9 @@ const { values, positionals } = parseArgs({
'suffix': {
type: 'string',
default: ''
+ },
+ 'web-snippet': {
+ type: 'boolean',
}
},
allowPositionals: true
@@ -29,6 +32,7 @@ if (values.help) {
console.log(' --watch, -w Watch src/ directory for changes and recompile')
console.log(' --suffix, -s Suffix to add to the output file name. Used for testing script size changes')
console.log(' --help Show this help message')
+ console.log(' --web-snippet Compile and output the web snippet')
process.exit(0);
}
@@ -49,6 +53,11 @@ const compileOptions = {
suffix: values.suffix
}
+if (values['web-snippet']) {
+ console.log(compileWebSnippet())
+ process.exit(0)
+}
+
await compileAll(compileOptions)
if (values.watch) {
diff --git a/tracker/compiler/index.js b/tracker/compiler/index.js
index b94ce8148a..beeb9ac0db 100644
--- a/tracker/compiler/index.js
+++ b/tracker/compiler/index.js
@@ -1,4 +1,4 @@
-import uglify from 'uglify-js'
+import { minifySync as swcMinify } from '@swc/core'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
@@ -18,6 +18,7 @@ const DEFAULT_GLOBALS = {
COMPILE_MANUAL: false,
COMPILE_FILE_DOWNLOADS: false,
COMPILE_PAGEVIEW_PROPS: false,
+ COMPILE_CUSTOM_PROPERTIES: false,
COMPILE_TAGGED_EVENTS: false,
COMPILE_REVENUE: false,
COMPILE_EXCLUSIONS: false,
@@ -68,6 +69,16 @@ export function compileFile(variant, options) {
}
}
+export function compileWebSnippet() {
+ const code = fs.readFileSync(relPath('../src/web-snippet.js')).toString()
+ return `
+<script>
+ ${minify(code)}
+ plausible.init()
+</script>
+ `
+}
+
function getVariantsToCompile(options) {
let targetVariants = variantsFile.legacyVariants.concat(variantsFile.manualVariants)
if (options.targets !== null) {
@@ -90,9 +101,10 @@ function getCode() {
}
function minify(baseCode, globals) {
- const result = uglify.minify(baseCode, {
+ const result = swcMinify(baseCode, {
compress: {
- global_defs: globals
+ global_defs: globals,
+ passes: 4
}
})
diff --git a/tracker/compiler/variants.json b/tracker/compiler/variants.json
index 699b3faff8..1410a071ce 100644
--- a/tracker/compiler/variants.json
+++ b/tracker/compiler/variants.json
@@ -12,7 +12,7 @@
"COMPILE_LOCAL": true,
"COMPILE_MANUAL": true,
"COMPILE_FILE_DOWNLOADS": true,
- "COMPILE_PAGEVIEW_PROPS": true,
+ "COMPILE_CUSTOM_PROPERTIES": true,
"COMPILE_TAGGED_EVENTS": true,
"COMPILE_REVENUE": true
}
diff --git a/tracker/package-lock.json b/tracker/package-lock.json
index 26cea1e5b4..ab86537bc9 100644
--- a/tracker/package-lock.json
+++ b/tracker/package-lock.json
@@ -6,11 +6,11 @@
"": {
"license": "MIT",
"dependencies": {
+ "@swc/core": "^1.11.24",
"chokidar": "^4.0.3",
"cli-progress": "^3.12.0",
"generatorics": "^1.1.0",
- "threads": "^1.7.0",
- "uglify-js": "^3.19.3"
+ "threads": "^1.7.0"
},
"devDependencies": {
"@playwright/test": "^1.49.1",
@@ -223,6 +223,219 @@
"node": ">=18"
}
},
+ "node_modules/@swc/core": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
+ "integrity": "sha512-MaQEIpfcEMzx3VWWopbofKJvaraqmL6HbLlw2bFZ7qYqYw3rkhM0cQVEgyzbHtTWwCwPMFZSC2DUbhlZgrMfLg==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@swc/counter": "^0.1.3",
+ "@swc/types": "^0.1.21"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/swc"
+ },
+ "optionalDependencies": {
+ "@swc/core-darwin-arm64": "1.11.24",
+ "@swc/core-darwin-x64": "1.11.24",
+ "@swc/core-linux-arm-gnueabihf": "1.11.24",
+ "@swc/core-linux-arm64-gnu": "1.11.24",
+ "@swc/core-linux-arm64-musl": "1.11.24",
+ "@swc/core-linux-x64-gnu": "1.11.24",
+ "@swc/core-linux-x64-musl": "1.11.24",
+ "@swc/core-win32-arm64-msvc": "1.11.24",
+ "@swc/core-win32-ia32-msvc": "1.11.24",
+ "@swc/core-win32-x64-msvc": "1.11.24"
+ },
+ "peerDependencies": {
+ "@swc/helpers": ">=0.5.17"
+ },
+ "peerDependenciesMeta": {
+ "@swc/helpers": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@swc/core-darwin-arm64": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.11.24.tgz",
+ "integrity": "sha512-dhtVj0PC1APOF4fl5qT2neGjRLgHAAYfiVP8poJelhzhB/318bO+QCFWAiimcDoyMgpCXOhTp757gnoJJrheWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-darwin-x64": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.11.24.tgz",
+ "integrity": "sha512-H/3cPs8uxcj2Fe3SoLlofN5JG6Ny5bl8DuZ6Yc2wr7gQFBmyBkbZEz+sPVgsID7IXuz7vTP95kMm1VL74SO5AQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-linux-arm-gnueabihf": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.11.24.tgz",
+ "integrity": "sha512-PHJgWEpCsLo/NGj+A2lXZ2mgGjsr96ULNW3+T3Bj2KTc8XtMUkE8tmY2Da20ItZOvPNC/69KroU7edyo1Flfbw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-linux-arm64-gnu": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.11.24.tgz",
+ "integrity": "sha512-C2FJb08+n5SD4CYWCTZx1uR88BN41ZieoHvI8A55hfVf2woT8+6ZiBzt74qW2g+ntZ535Jts5VwXAKdu41HpBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-linux-arm64-musl": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.11.24.tgz",
+ "integrity": "sha512-ypXLIdszRo0re7PNNaXN0+2lD454G8l9LPK/rbfRXnhLWDBPURxzKlLlU/YGd2zP98wPcVooMmegRSNOKfvErw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-linux-x64-gnu": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.11.24.tgz",
+ "integrity": "sha512-IM7d+STVZD48zxcgo69L0yYptfhaaE9cMZ+9OoMxirNafhKKXwoZuufol1+alEFKc+Wbwp+aUPe/DeWC/Lh3dg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-linux-x64-musl": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.11.24.tgz",
+ "integrity": "sha512-DZByJaMVzSfjQKKQn3cqSeqwy6lpMaQDQQ4HPlch9FWtDx/dLcpdIhxssqZXcR2rhaQVIaRQsCqwV6orSDGAGw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-win32-arm64-msvc": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.11.24.tgz",
+ "integrity": "sha512-Q64Ytn23y9aVDKN5iryFi8mRgyHw3/kyjTjT4qFCa8AEb5sGUuSj//AUZ6c0J7hQKMHlg9do5Etvoe61V98/JQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-win32-ia32-msvc": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.11.24.tgz",
+ "integrity": "sha512-9pKLIisE/Hh2vJhGIPvSoTK4uBSPxNVyXHmOrtdDot4E1FUUI74Vi8tFdlwNbaj8/vusVnb8xPXsxF1uB0VgiQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/core-win32-x64-msvc": {
+ "version": "1.11.24",
+ "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.11.24.tgz",
+ "integrity": "sha512-sybnXtOsdB+XvzVFlBVGgRHLqp3yRpHK7CrmpuDKszhj/QhmsaZzY/GHSeALlMtLup13M0gqbcQvsTNlAHTg3w==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@swc/counter": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
+ "integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@swc/types": {
+ "version": "0.1.21",
+ "resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.21.tgz",
+ "integrity": "sha512-2YEtj5HJVbKivud9N4bpPBAyZhj4S2Ipe5LkUG94alTpr7in/GU/EARgPAd3BwU+YOmFVJC2+kjqhGRi3r0ZpQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@swc/counter": "^0.1.3"
+ }
+ },
"node_modules/@types/estree": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",
@@ -2073,17 +2286,6 @@
"node": ">= 0.6"
}
},
- "node_modules/uglify-js": {
- "version": "3.19.3",
- "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz",
- "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==",
- "bin": {
- "uglifyjs": "bin/uglifyjs"
- },
- "engines": {
- "node": ">=0.8.0"
- }
- },
"node_modules/undici-types": {
"version": "6.20.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
diff --git a/tracker/package.json b/tracker/package.json
index c7294f3ca2..9b3b9dbe2f 100644
--- a/tracker/package.json
+++ b/tracker/package.json
@@ -1,5 +1,5 @@
{
- "tracker_script_version": 9,
+ "tracker_script_version": 10,
"type": "module",
"scripts": {
"deploy": "node compile.js",
@@ -9,11 +9,11 @@
},
"license": "MIT",
"dependencies": {
+ "@swc/core": "^1.11.24",
"chokidar": "^4.0.3",
"cli-progress": "^3.12.0",
"generatorics": "^1.1.0",
- "threads": "^1.7.0",
- "uglify-js": "^3.19.3"
+ "threads": "^1.7.0"
},
"devDependencies": {
"@playwright/test": "^1.49.1",
diff --git a/tracker/src/plausible.js b/tracker/src/plausible.js
index 64c3f7e642..0b17b775cf 100644
--- a/tracker/src/plausible.js
+++ b/tracker/src/plausible.js
@@ -1,300 +1,160 @@
- 'use strict';
+var location = window.location
+var document = window.document
- var location = window.location
- var document = window.document
-
- if (COMPILE_COMPAT) {
+if (COMPILE_COMPAT) {
var scriptEl = document.getElementById('plausible');
- } else {
+} else {
var scriptEl = document.currentScript;
- }
-
- var config = {}
-
- if (COMPILE_CONFIG) {
- config = "<%= @config_json %>"
- }
-
- var endpoint = COMPILE_CONFIG ? config.endpoint : (scriptEl.getAttribute('data-api') || defaultEndpoint())
- var dataDomain = COMPILE_CONFIG ? config.domain : scriptEl.getAttribute('data-domain')
-
- function onIgnoredEvent(eventName, reason, options) {
- if (reason) console.warn('Ignoring Event: ' + reason);
- options && options.callback && options.callback()
-
- if (eventName === 'pageview') {
- currentEngagementIgnored = true
- }
- }
-
- function defaultEndpoint() {
- if (COMPILE_COMPAT) {
- var pathArray = scriptEl.src.split( '/' );
- var protocol = pathArray[0];
- var host = pathArray[2];
- return protocol + '//' + host + '/api/event';
- } else {
- return new URL(scriptEl.src).origin + '/api/event'
- }
- }
+}
- var currentEngagementIgnored
- var currentEngagementURL = location.href
- var currentEngagementProps = {}
- var currentEngagementMaxScrollDepth = -1
-
- // Multiple pageviews might be sent by the same script when the page
- // uses client-side routing (e.g. hash or history-based). This flag
- // prevents registering multiple listeners in those cases.
- var listeningOnEngagement = false
-
- // Timestamp indicating when this particular page last became visible.
- // Reset during pageviews, set to null when page is closed.
- var runningEngagementStart = null
-
- // When page is hidden, this 'engaged' time is saved to this variable
- var currentEngagementTime = 0
-
- function getDocumentHeight() {
- var body = document.body || {}
- var el = document.documentElement || {}
- return Math.max(
- body.scrollHeight || 0,
- body.offsetHeight || 0,
- body.clientHeight || 0,
- el.scrollHeight || 0,
- el.offsetHeight || 0,
- el.clientHeight || 0
- )
- }
+var config = {}
- function getCurrentScrollDepthPx() {
- var body = document.body || {}
- var el = document.documentElement || {}
- var viewportHeight = window.innerHeight || el.clientHeight || 0
- var scrollTop = window.scrollY || el.scrollTop || body.scrollTop || 0
+if (COMPILE_CONFIG) {
+ config = "<%= @config_js %>"
+}
- return currentDocumentHeight <= viewportHeight ? currentDocumentHeight : scrollTop + viewportHeight
- }
+var endpoint
+var dataDomain
- function getEngagementTime() {
- if (runningEngagementStart) {
- return currentEngagementTime + (Date.now() - runningEngagementStart)
- } else {
- return currentEngagementTime
- }
- }
+// Exported public function
+function trigger(eventName, options) {
+ var isPageview = eventName === 'pageview'
- var currentDocumentHeight = getDocumentHeight()
- var maxScrollDepthPx = getCurrentScrollDepthPx()
-
- window.addEventListener('load', function () {
+ if (isPageview && listeningOnEngagement) {
+ // If we're listening on engagement already, at least one pageview
+ // has been sent by the current script (i.e. it's most likely a SPA).
+ // Trigger an engagement marking the "exit from the previous page".
+ triggerEngagement()
currentDocumentHeight = getDocumentHeight()
-
- // Update the document height again after every 200ms during the
- // next 3 seconds. This makes sure dynamically loaded content is
- // also accounted for.
- var count = 0
- var interval = setInterval(function () {
- currentDocumentHeight = getDocumentHeight()
- if (++count === 15) {clearInterval(interval)}
- }, 200)
-
- })
-
- document.addEventListener('scroll', function() {
- currentDocumentHeight = getDocumentHeight()
- var currentScrollDepthPx = getCurrentScrollDepthPx()
-
- if (currentScrollDepthPx > maxScrollDepthPx) {
- maxScrollDepthPx = currentScrollDepthPx
- }
- })
-
- function triggerEngagement() {
- var engagementTime = getEngagementTime()
-
- /*
- We send engagements if there's new relevant engagement information to share:
- - If the user has scrolled more than the previously sent max scroll depth.
- - If the user has been engaged for more than 3 seconds since the last engagement event.
-
- The first engagement event is always sent due to containing at least the initial scroll depth.
-
- Also, we don't send engagements if the current pageview is ignored (onIgnoredEvent)
- */
- if (!currentEngagementIgnored && (currentEngagementMaxScrollDepth < maxScrollDepthPx || engagementTime >= 3000)) {
- currentEngagementMaxScrollDepth = maxScrollDepthPx
-
- var payload = {
- n: 'engagement',
- sd: Math.round((maxScrollDepthPx / currentDocumentHeight) * 100),
- d: dataDomain,
- u: currentEngagementURL,
- p: currentEngagementProps,
- e: engagementTime,
- v: COMPILE_TRACKER_SCRIPT_VERSION
- }
-
- // Reset current engagement time metrics. They will restart upon when page becomes visible or the next SPA pageview
- runningEngagementStart = null
- currentEngagementTime = 0
-
- if (COMPILE_HASH && (!COMPILE_CONFIG || config.hash)) {
- payload.h = 1
- }
-
- sendRequest(endpoint, payload)
- }
+ maxScrollDepthPx = getCurrentScrollDepthPx()
}
- function onVisibilityChange() {
- if (document.visibilityState === 'visible' && document.hasFocus() && runningEngagementStart === null) {
- runningEngagementStart = Date.now()
- } else if (document.visibilityState === 'hidden' || !document.hasFocus()) {
- // Tab went back to background or lost focus. Save the engaged time so far
- currentEngagementTime = getEngagementTime()
- runningEngagementStart = null
-
- triggerEngagement()
- }
- }
-
- function registerEngagementListener() {
- if (!listeningOnEngagement) {
- // Only register visibilitychange listener only after initial page load and pageview
- document.addEventListener('visibilitychange', onVisibilityChange)
- window.addEventListener('blur', onVisibilityChange)
- window.addEventListener('focus', onVisibilityChange)
- listeningOnEngagement = true
- }
- }
-
- function trigger(eventName, options) {
- var isPageview = eventName === 'pageview'
-
- if (isPageview && listeningOnEngagement) {
- // If we're listening on engagement already, at least one pageview
- // has been sent by the current script (i.e. it's most likely a SPA).
- // Trigger an engagement marking the "exit from the previous page".
- triggerEngagement()
- currentDocumentHeight = getDocumentHeight()
- maxScrollDepthPx = getCurrentScrollDepthPx()
- }
-
- if (!(COMPILE_LOCAL && (!COMPILE_CONFIG || config.local))) {
+ if (!(COMPILE_LOCAL && (!COMPILE_CONFIG || config.local))) {
if (/^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/.test(location.hostname) || location.protocol === 'file:') {
- return onIgnoredEvent(eventName, 'localhost', options)
+ return onIgnoredEvent(eventName, options, 'localhost')
}
if ((window._phantom || window.__nightmare || window.navigator.webdriver || window.Cypress) && !window.__plausible) {
- return onIgnoredEvent(eventName, null, options)
+ return onIgnoredEvent(eventName, options)
}
+ }
+ try {
+ if (window.localStorage.plausible_ignore === 'true') {
+ return onIgnoredEvent(eventName, options, 'localStorage flag')
}
- try {
- if (window.localStorage.plausible_ignore === 'true') {
- return onIgnoredEvent(eventName, 'localStorage flag', options)
- }
- } catch (e) {
+ } catch (e) {
- }
- if (COMPILE_EXCLUSIONS && (!COMPILE_CONFIG || config.exclusions)) {
+ }
+ if (COMPILE_EXCLUSIONS) {
var dataIncludeAttr = scriptEl && scriptEl.getAttribute('data-include')
var dataExcludeAttr = scriptEl && scriptEl.getAttribute('data-exclude')
- if (isPageview) {
- var isIncluded = !dataIncludeAttr || (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))
- var isExcluded = dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)
-
- if (!isIncluded || isExcluded) return onIgnoredEvent(eventName, 'exclusion rule', options)
- }
function pathMatches(wildcardPath) {
var actualPath = location.pathname
if (COMPILE_HASH && (!COMPILE_CONFIG || config.hash)) {
- actualPath += location.hash
+ actualPath += location.hash
}
return actualPath.match(new RegExp('^' + wildcardPath.trim().replace(/\*\*/g, '.*').replace(/([^\.])\*/g, '$1[^\\s\/]*') + '\/?$'))
}
+
+ if (isPageview) {
+ var isIncluded = !dataIncludeAttr || (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))
+ var isExcluded = dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)
+
+ if (!isIncluded || isExcluded) return onIgnoredEvent(eventName, 'exclusion rule', options)
}
+ }
- var payload = {}
- payload.n = eventName
- payload.v = COMPILE_TRACKER_SCRIPT_VERSION
+ var payload = {}
+ payload.n = eventName
+ payload.v = COMPILE_TRACKER_SCRIPT_VERSION
- if (COMPILE_MANUAL && (!COMPILE_CONFIG || config.manual)) {
+ if (COMPILE_MANUAL && (!COMPILE_CONFIG || config.manual)) {
var customURL = options && options.u
payload.u = customURL ? customURL : location.href
- } else {
+ } else {
payload.u = location.href
- }
+ }
- payload.d = dataDomain
- payload.r = document.referrer || null
- if (options && options.meta) {
- payload.m = JSON.stringify(options.meta)
- }
- if (options && options.props) {
- payload.p = options.props
- }
- if (options && options.interactive === false) {
- payload.i = false
- }
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ payload.d = dataDomain
+ payload.r = document.referrer || null
+ if (options && options.meta) {
+ payload.m = JSON.stringify(options.meta)
+ }
+ if (options && options.props) {
+ payload.p = options.props
+ }
+ if (options && options.interactive === false) {
+ payload.i = false
+ }
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
if (options && options.revenue) {
payload.$ = options.revenue
}
- }
+ }
- if (COMPILE_PAGEVIEW_PROPS && (!COMPILE_CONFIG || config.pageviewProps)) {
+ if (COMPILE_PAGEVIEW_PROPS) {
var propAttributes = scriptEl.getAttributeNames().filter(function (name) {
return name.substring(0, 6) === 'event-'
})
var props = payload.p || {}
- propAttributes.forEach(function(attribute) {
+ propAttributes.forEach(function (attribute) {
var propKey = attribute.replace('event-', '')
var propValue = scriptEl.getAttribute(attribute)
props[propKey] = props[propKey] || propValue
})
payload.p = props
- }
+ }
- if (COMPILE_HASH && (!COMPILE_CONFIG || config.hash)) {
- payload.h = 1
+ // Track custom properties for pageviews and other events
+ if (COMPILE_CUSTOM_PROPERTIES && config.customProperties) {
+ var props = config.customProperties
+ if (typeof props === 'function') {
+ props = config.customProperties(eventName)
}
- if (isPageview) {
- currentEngagementIgnored = false
- currentEngagementURL = payload.u
- currentEngagementProps = payload.p
- currentEngagementMaxScrollDepth = -1
- currentEngagementTime = 0
- runningEngagementStart = Date.now()
- registerEngagementListener()
+ if (typeof props === 'object') {
+ payload.p = Object.assign({}, props, payload.p)
}
+ }
- sendRequest(endpoint, payload, options)
+ if (COMPILE_HASH && (!COMPILE_CONFIG || config.hash)) {
+ payload.h = 1
}
- function sendRequest(endpoint, payload, options) {
- if (COMPILE_COMPAT) {
+ if (isPageview) {
+ currentEngagementIgnored = false
+ currentEngagementURL = payload.u
+ currentEngagementProps = payload.p
+ currentEngagementMaxScrollDepth = -1
+ currentEngagementTime = 0
+ runningEngagementStart = Date.now()
+ registerEngagementListener()
+ }
+
+ sendRequest(endpoint, payload, options)
+}
+
+function sendRequest(endpoint, payload, options) {
+ if (COMPILE_COMPAT) {
var request = new XMLHttpRequest();
request.open('POST', endpoint, true);
request.setRequestHeader('Content-Type', 'text/plain');
request.send(JSON.stringify(payload));
- request.onreadystatechange = function() {
+ request.onreadystatechange = function () {
if (request.readyState === 4) {
- options && options.callback && options.callback({status: request.status})
+ options && options.callback && options.callback({ status: request.status })
}
}
- } else {
+ } else {
if (window.fetch) {
fetch(endpoint, {
method: 'POST',
@@ -303,45 +163,211 @@
},
keepalive: true,
body: JSON.stringify(payload)
- }).then(function(response) {
- options && options.callback && options.callback({status: response.status})
- }).catch(function() {})
+ }).then(function (response) {
+ options && options.callback && options.callback({ status: response.status })
+ }).catch(function () { })
+ }
+ }
+}
+
+/* Engagement tracking variables and functions */
+
+// Multiple pageviews might be sent by the same script when the page
+// uses client-side routing (e.g. hash or history-based). This flag
+// prevents registering multiple listeners in those cases.
+var listeningOnEngagement = false
+
+var currentEngagementIgnored
+var currentEngagementURL = location.href
+var currentEngagementProps = {}
+var currentEngagementMaxScrollDepth = -1
+
+// Timestamp indicating when this particular page last became visible.
+// Reset during pageviews, set to 0 when page is closed.
+var runningEngagementStart = 0
+
+// When page is hidden, this 'engaged' time is saved to this variable
+var currentEngagementTime = 0
+
+function triggerEngagement() {
+ var engagementTime = getEngagementTime()
+
+ /*
+ We send engagements if there's new relevant engagement information to share:
+ - If the user has scrolled more than the previously sent max scroll depth.
+ - If the user has been engaged for more than 3 seconds since the last engagement event.
+
+ The first engagement event is always sent due to containing at least the initial scroll depth.
+
+ Also, we don't send engagements if the current pageview is ignored (onIgnoredEvent)
+ */
+ if (!currentEngagementIgnored && (currentEngagementMaxScrollDepth < maxScrollDepthPx || engagementTime >= 3000)) {
+ currentEngagementMaxScrollDepth = maxScrollDepthPx
+
+ var payload = {
+ n: 'engagement',
+ sd: Math.round((maxScrollDepthPx / currentDocumentHeight) * 100),
+ d: dataDomain,
+ u: currentEngagementURL,
+ p: currentEngagementProps,
+ e: engagementTime,
+ v: COMPILE_TRACKER_SCRIPT_VERSION
}
+
+ // Reset current engagement time metrics. They will restart upon when page becomes visible or the next SPA pageview
+ runningEngagementStart = 0
+ currentEngagementTime = 0
+
+ if (COMPILE_HASH && (!COMPILE_CONFIG || config.hash)) {
+ payload.h = 1
}
+
+ sendRequest(endpoint, payload)
}
+}
- var queue = (window.plausible && window.plausible.q) || []
- window.plausible = trigger
- for (var i = 0; i < queue.length; i++) {
- trigger.apply(this, queue[i])
+function onVisibilityChange() {
+ if (document.visibilityState === 'visible' && document.hasFocus() && runningEngagementStart === 0) {
+ runningEngagementStart = Date.now()
+ } else if (document.visibilityState === 'hidden' || !document.hasFocus()) {
+ // Tab went back to background or lost focus. Save the engaged time so far
+ currentEngagementTime = getEngagementTime()
+ runningEngagementStart = 0
+
+ triggerEngagement()
}
+}
+
+function registerEngagementListener() {
+ if (!listeningOnEngagement) {
+ // Only register visibilitychange listener only after initial page load and pageview
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ window.addEventListener('blur', onVisibilityChange)
+ window.addEventListener('focus', onVisibilityChange)
+ listeningOnEngagement = true
+ }
+}
+
+function getEngagementTime() {
+ if (runningEngagementStart) {
+ return currentEngagementTime + (Date.now() - runningEngagementStart)
+ } else {
+ return currentEngagementTime
+ }
+}
+
+
+var currentDocumentHeight
+var maxScrollDepthPx
+
+function getDocumentHeight() {
+ var body = document.body || {}
+ var el = document.documentElement || {}
+ return Math.max(
+ body.scrollHeight || 0,
+ body.offsetHeight || 0,
+ body.clientHeight || 0,
+ el.scrollHeight || 0,
+ el.offsetHeight || 0,
+ el.clientHeight || 0
+ )
+}
+
+function getCurrentScrollDepthPx() {
+ var body = document.body || {}
+ var el = document.documentElement || {}
+ var viewportHeight = window.innerHeight || el.clientHeight || 0
+ var scrollTop = window.scrollY || el.scrollTop || body.scrollTop || 0
+
+ return currentDocumentHeight <= viewportHeight ? currentDocumentHeight : scrollTop + viewportHeight
+}
+
+function onIgnoredEvent(eventName, options, reason) {
+ if (reason) console.warn('Ignoring Event: ' + reason);
+ options && options.callback && options.callback()
+
+ if (eventName === 'pageview') {
+ currentEngagementIgnored = true
+ }
+}
+
+function defaultEndpoint() {
+ if (COMPILE_COMPAT) {
+ var pathArray = scriptEl.src.split('/');
+ var protocol = pathArray[0];
+ var host = pathArray[2];
+ return protocol + '//' + host + '/api/event';
+ } else {
+ return new URL(scriptEl.src).origin + '/api/event'
+ }
+}
+
+function init(overrides) {
+ if (COMPILE_CONFIG && window.plausible && window.plausible.l) {
+ console.warn('Plausible analytics script was already initialized, skipping init')
+ return
+ }
+
+ // Explicitly set dataDomain before any overrides are applied as `plausible-main` does not support overriding it
+ dataDomain = COMPILE_CONFIG ? config.domain : scriptEl.getAttribute('data-domain')
+
+ if (COMPILE_CONFIG) {
+ Object.assign(config, overrides)
+ }
+
+ endpoint = COMPILE_CONFIG ? config.endpoint : (scriptEl.getAttribute('data-api') || defaultEndpoint())
+
+ currentDocumentHeight = getDocumentHeight()
+ maxScrollDepthPx = getCurrentScrollDepthPx()
+
+ window.addEventListener('load', function () {
+ currentDocumentHeight = getDocumentHeight()
+
+ // Update the document height again after every 200ms during the
+ // next 3 seconds. This makes sure dynamically loaded content is
+ // also accounted for.
+ var count = 0
+ var interval = setInterval(function () {
+ currentDocumentHeight = getDocumentHeight()
+ if (++count === 15) { clearInterval(interval) }
+ }, 200)
+ })
+
+ document.addEventListener('scroll', function () {
+ currentDocumentHeight = getDocumentHeight()
+ var currentScrollDepthPx = getCurrentScrollDepthPx()
+
+ if (currentScrollDepthPx > maxScrollDepthPx) {
+ maxScrollDepthPx = currentScrollDepthPx
+ }
+ })
if (!(COMPILE_MANUAL && (!COMPILE_CONFIG || config.manual))) {
var lastPage;
function page(isSPANavigation) {
if (!(COMPILE_HASH && (!COMPILE_CONFIG || config.hash))) {
- if (isSPANavigation && lastPage === location.pathname) return;
+ if (isSPANavigation && lastPage === location.pathname) return;
}
lastPage = location.pathname
trigger('pageview')
}
- var onSPANavigation = function() {page(true)}
+ var onSPANavigation = function () { page(true) }
if (COMPILE_HASH && (!COMPILE_CONFIG || config.hash)) {
- window.addEventListener('hashchange', onSPANavigation)
+ window.addEventListener('hashchange', onSPANavigation)
} else {
- var his = window.history
- if (his.pushState) {
- var originalPushState = his['pushState']
- his.pushState = function() {
- originalPushState.apply(this, arguments)
- onSPANavigation();
+ var his = window.history
+ if (his.pushState) {
+ var originalPushState = his['pushState']
+ his.pushState = function () {
+ originalPushState.apply(this, arguments)
+ onSPANavigation();
+ }
+ window.addEventListener('popstate', onSPANavigation)
}
- window.addEventListener('popstate', onSPANavigation)
- }
}
function handleVisibilityChange() {
@@ -356,7 +382,7 @@
page()
}
- window.addEventListener('pageshow', function(event) {
+ window.addEventListener('pageshow', function (event) {
if (event.persisted) {
// Page was restored from bfcache - trigger a pageview
page();
@@ -364,235 +390,258 @@
})
}
-if (COMPILE_OUTBOUND_LINKS || COMPILE_FILE_DOWNLOADS || COMPILE_TAGGED_EVENTS) {
- function getLinkEl(link) {
- while (link && (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)) {
- link = link.parentNode
+ if (COMPILE_OUTBOUND_LINKS || COMPILE_FILE_DOWNLOADS || COMPILE_TAGGED_EVENTS) {
+ function getLinkEl(link) {
+ while (link && (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)) {
+ link = link.parentNode
+ }
+ return link
}
- 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 }
+ function isLink(element) {
+ return element && element.tagName && element.tagName.toLowerCase() === 'a'
+ }
- var link = getLinkEl(event.target)
- var hrefWithoutQuery = link && link.href && link.href.split('?')[0]
+ function shouldFollowLink(event, link) {
+ // If default has been prevented by an external script, Plausible should not intercept navigation.
+ if (event.defaultPrevented) { return false }
- if (COMPILE_TAGGED_EVENTS && (!COMPILE_CONFIG || config.taggedEvents)) {
- if (isElementOrParentTagged(link, 0)) {
- // Return to prevent sending multiple events with the same action.
- // Clicks on tagged links are handled by another function.
- return
- }
+ 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
}
- if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {
- if (isOutboundLink(link)) {
- return sendLinkClickEvent(event, link, { name: 'Outbound Link: Click', props: { url: link.href } })
- }
- }
+ var MIDDLE_MOUSE_BUTTON = 1
- if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {
- if (isDownloadToTrack(hrefWithoutQuery)) {
- return sendLinkClickEvent(event, link, { name: 'File Download', props: { url: hrefWithoutQuery } })
- }
- }
- }
+ function handleLinkClickEvent(event) {
+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
- function sendLinkClickEvent(event, link, eventAttrs) {
- var followedLink = false
+ var link = getLinkEl(event.target)
+ var hrefWithoutQuery = link && link.href && link.href.split('?')[0]
- function followLink() {
- if (!followedLink) {
- followedLink = true
- window.location = link.href
+ if (COMPILE_TAGGED_EVENTS && (!COMPILE_CONFIG || config.taggedEvents)) {
+ 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 (shouldFollowLink(event, link)) {
- var attrs = { props: eventAttrs.props, callback: followLink }
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
- attrs.revenue = eventAttrs.revenue
+ if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {
+ if (isOutboundLink(link)) {
+ return sendLinkClickEvent(event, link, { name: 'Outbound Link: Click', props: { url: link.href } })
+ }
}
- plausible(eventAttrs.name, attrs)
- setTimeout(followLink, 5000)
- event.preventDefault()
- } else {
- var attrs = { props: eventAttrs.props }
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
- attrs.revenue = eventAttrs.revenue
+
+ if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {
+ if (isDownloadToTrack(hrefWithoutQuery)) {
+ return sendLinkClickEvent(event, link, { name: 'File Download', props: { url: hrefWithoutQuery } })
+ }
}
- plausible(eventAttrs.name, attrs)
}
- }
- document.addEventListener('click', handleLinkClickEvent)
- document.addEventListener('auxclick', handleLinkClickEvent)
+ function sendLinkClickEvent(event, link, eventAttrs) {
+ var followedLink = false
- if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {
- function isOutboundLink(link) {
- return link && link.href && link.host && link.host !== location.host
- }
- }
-
- if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {
- 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', 'dmg']
- 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 followLink() {
+ if (!followedLink) {
+ followedLink = true
+ window.location = link.href
+ }
+ }
- function isDownloadToTrack(url) {
- if (!url) { return false }
+ if (shouldFollowLink(event, link)) {
+ var attrs = { props: eventAttrs.props, callback: followLink }
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ plausible(eventAttrs.name, attrs)
+ setTimeout(followLink, 5000)
+ event.preventDefault()
+ } else {
+ var attrs = { props: eventAttrs.props }
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ plausible(eventAttrs.name, attrs)
+ }
+ }
- var fileType = url.split('.').pop();
- return fileTypesToTrack.some(function (fileTypeToTrack) {
- return fileTypeToTrack === fileType
- })
- }
- }
+ document.addEventListener('click', handleLinkClickEvent)
+ document.addEventListener('auxclick', handleLinkClickEvent)
- if (COMPILE_TAGGED_EVENTS && (!COMPILE_CONFIG || config.taggedEvents)) {
- // 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: {} }
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
- eventAttrs.revenue = {}
+ if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {
+ function isOutboundLink(link) {
+ return link && link.href && link.host && link.host !== location.host
+ }
}
- var classList = taggedElement && taggedElement.classList
- if (!classList) { return eventAttrs }
-
- for (var i = 0; i < classList.length; i++) {
- var className = classList.item(i)
+ if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {
+ 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', 'dmg']
+ 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
+ })
+ }
+ }
- var matchList = className.match(/plausible-event-(.+)(=|--)(.+)/)
- if (matchList) {
- var key = matchList[1]
- var value = matchList[3].replace(/\+/g, ' ')
+ if (COMPILE_TAGGED_EVENTS && (!COMPILE_CONFIG || config.taggedEvents)) {
+ // 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: {} }
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ eventAttrs.revenue = {}
+ }
- if (key.toLowerCase() == 'name') {
- eventAttrs.name = value
- } else {
- eventAttrs.props[key] = value
+ 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) {
+ var key = matchList[1]
+ var value = matchList[3].replace(/\+/g, ' ')
+
+ if (key.toLowerCase() == 'name') {
+ eventAttrs.name = value
+ } else {
+ eventAttrs.props[key] = value
+ }
+ }
+
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ var revenueMatchList = className.match(/plausible-revenue-(.+)(=|--)(.+)/)
+ if (revenueMatchList) {
+ var key = revenueMatchList[1]
+ var value = revenueMatchList[3]
+ eventAttrs.revenue[key] = value
+ }
+ }
}
- }
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
- var revenueMatchList = className.match(/plausible-revenue-(.+)(=|--)(.+)/)
- if (revenueMatchList) {
- var key = revenueMatchList[1]
- var value = revenueMatchList[3]
- eventAttrs.revenue[key] = value
- }
+ return eventAttrs
}
- }
-
- return eventAttrs
- }
- function handleTaggedFormSubmitEvent(event) {
- var form = event.target
- var eventAttrs = getTaggedEventAttributes(form)
- if (!eventAttrs.name) { return }
+ function handleTaggedFormSubmitEvent(event) {
+ var form = event.target
+ var eventAttrs = getTaggedEventAttributes(form)
+ if (!eventAttrs.name) { return }
- event.preventDefault()
- var formSubmitted = false
+ event.preventDefault()
+ var formSubmitted = false
- function submitForm() {
- if (!formSubmitted) {
- formSubmitted = true
- form.submit()
- }
- }
+ function submitForm() {
+ if (!formSubmitted) {
+ formSubmitted = true
+ form.submit()
+ }
+ }
- setTimeout(submitForm, 5000)
+ setTimeout(submitForm, 5000)
- var attrs = { props: eventAttrs.props, callback: submitForm }
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
- attrs.revenue = eventAttrs.revenue
- }
- plausible(eventAttrs.name, attrs)
- }
+ var attrs = { props: eventAttrs.props, callback: submitForm }
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ plausible(eventAttrs.name, attrs)
+ }
- function isForm(element) {
- return element && element.tagName && element.tagName.toLowerCase() === 'form'
- }
+ function isForm(element) {
+ return element && element.tagName && element.tagName.toLowerCase() === 'form'
+ }
- var PARENTS_TO_SEARCH_LIMIT = 3
+ var PARENTS_TO_SEARCH_LIMIT = 3
- function handleTaggedElementClickEvent(event) {
- if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
+ function handleTaggedElementClickEvent(event) {
+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
- var clicked = event.target
+ 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 }
+ 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
- }
+ // 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 (taggedElement) {
+ var eventAttrs = getTaggedEventAttributes(taggedElement)
+
+ if (clickedLink) {
+ // if the clicked tagged element is a link, we attach the `url` property
+ // automatically for user convenience
+ eventAttrs.props.url = clickedLink.href
+ sendLinkClickEvent(event, clickedLink, eventAttrs)
+ } else {
+ var attrs = {}
+ attrs.props = eventAttrs.props
+ if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ plausible(eventAttrs.name, attrs)
+ }
+ }
+ }
- if (clickedLink) {
- // if the clicked tagged element is a link, we attach the `url` property
- // automatically for user convenience
- eventAttrs.props.url = clickedLink.href
- sendLinkClickEvent(event, clickedLink, eventAttrs)
- } else {
- var attrs = {}
- attrs.props = eventAttrs.props
- if (COMPILE_REVENUE && (!COMPILE_CONFIG || config.revenue)) {
- attrs.revenue = eventAttrs.revenue
+ 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 }
+ }
}
- plausible(eventAttrs.name, attrs)
+ return false
}
- }
- }
- 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 }
+ 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)
}
- 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)
+ // Call `trigger` for any events that were queued via plausible('event') before `init` was called
+ var queue = (window.plausible && window.plausible.q) || []
+ for (var i = 0; i < queue.length; i++) {
+ trigger.apply(this, queue[i])
}
- document.addEventListener('submit', handleTaggedFormSubmitEvent)
- document.addEventListener('click', handleTaggedElementClickEvent)
- document.addEventListener('auxclick', handleTaggedElementClickEvent)
+ window.plausible = trigger
+ window.plausible.init = init
+ window.plausible.l = true
+}
+
+if (COMPILE_CONFIG) {
+ window.plausible = (window.plausible || {})
+
+ if (plausible.o) {
+ init(plausible.o)
}
+
+ plausible.init = init
+} else {
+ init()
}
diff --git a/tracker/src/web-snippet.js b/tracker/src/web-snippet.js
new file mode 100644
index 0000000000..24a272e70d
--- /dev/null
+++ b/tracker/src/web-snippet.js
@@ -0,0 +1,19 @@
+// This snippet is shown to users to install plausible tracker script
+
+//<script>
+window.plausible = window.plausible || function() {
+ (window.plausible.q = window.plausible.q || []).push(arguments)
+}
+window.plausible.init = function(overrides) {
+ window.plausible.o = overrides || {}
+}
+
+var script = document.createElement("script")
+script.type="text/javascript"
+script.defer=true
+script.src="<%= plausible_script_url %>"
+var r = document.getElementsByTagName("script")[0]
+r.parentNode.insertBefore(script, r);
+
+// plausible.init()
+//</script>
diff --git a/tracker/test/engagement.spec.js b/tracker/test/engagement.spec.js
index 3b2a2b774e..b6e40a7943 100644
--- a/tracker/test/engagement.spec.js
+++ b/tracker/test/engagement.spec.js
@@ -155,12 +155,31 @@ test.describe('engagement events', () => {
test('sends an event with the same props as pageview (pageview-props extension)', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement-pageview-props.html'),
- expectedRequests: [{n: 'pageview', p: {author: 'John'}}],
+ expectedRequests: [{n: 'pageview', p: {author: 'John', index: "0"}}],
})
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', p: {author: 'John'}}]
+ expectedRequests: [{n: 'engagement', p: {author: 'John', index: "0"}}]
+ })
+ })
+
+ test('pageview props with custom events and values changing mid-view (pageview-props extension)', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/engagement-pageview-props.html'),
+ expectedRequests: [{n: 'pageview', p: {author: 'John', index: "0"}}],
+ })
+
+ await page.click('#increment-event-index')
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#custom-event-button'),
+ expectedRequests: [{n: 'Custom event', p: {author: 'Karl', index: "1"}}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'engagement', p: {author: 'John', index: "0"}}]
})
})
@@ -209,8 +228,8 @@ test.describe('engagement events', () => {
},
expectedRequests: [
{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement-pageview-props.html`, p: {author: 'John'}},
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-pageview-props.html`, p: {author: 'John'}},
+ {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement-pageview-props.html`, p: {author: 'John', index: "0"}},
+ {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-pageview-props.html`, p: {author: 'John', index: "0"}},
{n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement.html`}
],
responseDelay: 1000
diff --git a/tracker/test/fixtures/engagement-pageview-props.html b/tracker/test/fixtures/engagement-pageview-props.html
index 866425bc86..9306daa922 100644
--- a/tracker/test/fixtures/engagement-pageview-props.html
+++ b/tracker/test/fixtures/engagement-pageview-props.html
@@ -11,14 +11,18 @@
<body>
<a id="navigate-away" href="/manual.html">Navigate away</a>
- <button id="back-button-trigger">Back button</button>
+ <button id="custom-event-button" onclick="plausible('Custom event', { props: { author: 'Karl' } })">Custom event</button>
+ <button id="back-button-trigger" onclick="window.history.back()">Back button</button>
+ <button id="increment-event-index" onclick="increment()">Increment event index</button>
</body>
<script>
- document.addEventListener('click', (e) => {
- if (e.target.id === 'back-button-trigger') {
- window.history.back()
- }
- })
+ var i = 0
+
+ function increment() {
+ document.getElementsByTagName('script')[0].setAttribute("event-index", i++)
+ }
+
+ increment()
</script>
</html>
diff --git a/tracker/test/fixtures/plausible-main.html b/tracker/test/fixtures/plausible-main.html
index 635937942b..4231a32c5e 100644
--- a/tracker/test/fixtures/plausible-main.html
+++ b/tracker/test/fixtures/plausible-main.html
@@ -5,7 +5,7 @@
<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>
+ <title>plausible-main.js tests</title>
</head>
<body>
@@ -15,26 +15,42 @@
<a id="manual-pageview" onclick="plausible('pageview', { u: '/:test-plausible-main' })">Manual pageview</a>
+ <a id="custom-event" onclick="plausible('Custom event', { props: { author: 'Karl' } })">Custom event</a>
+
<button id="tagged-event" class="plausible-event-name=Purchase plausible-event-foo=bar plausible-revenue-currency=EUR plausible-revenue-amount=13.32">
Tagged event
</button>
- <script>window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }</script>
<script>
const params = new URLSearchParams(window.location.search)
- if (params.has('before_script_loaded')) {
- const beforeScriptLoaded = params.get('before_script_loaded')
- eval(beforeScriptLoaded)
- }
- // Trick to load the script with the passed config
- const config = params.get('script_config')
- const script = document.createElement('script')
- script.src = `/tracker/js/plausible-main.js?script_config=${encodeURIComponent(config)}`
- script.setAttribute('event-some-prop', '456')
+ window.pageviewProps = { someProp: 123 }
+
+ window.includePlausibleScript = function(src) {
+ // Base snippet (minus script inclusion)
+ window.plausible=window.plausible||function(){(window.plausible.q = window.plausible.q || []).push(arguments)}
+ window.plausible.init = function(overrides) { window.plausible.o = overrides || {} }
+
+ if (params.has('beforeScriptLoaded')) {
+ const beforeScriptLoaded = params.get('beforeScriptLoaded')
+ eval(beforeScriptLoaded)
+ }
+
+ if (!params.has('skipPlausibleInit')) {
+ plausible.init()
+ }
+
+ // Load the script with the passed config
+ const config = params.get('script_config')
+ const script = document.createElement('script')
+ script.src = `/tracker/js/plausible-main.js?script_config=${encodeURIComponent(config)}`
+
+ var r = document.getElementsByTagName("script")[0]
+ r.parentNode.insertBefore(script, r);
+ }
- document.body.appendChild(script)
+ includePlausibleScript()
</script>
</body>
</html>
diff --git a/tracker/test/plausible-main.spec.js b/tracker/test/plausible-main.spec.js
index b3aa3d47fc..9fbe7beba2 100644
--- a/tracker/test/plausible-main.spec.js
+++ b/tracker/test/plausible-main.spec.js
@@ -10,9 +10,9 @@ import {
hideAndShowCurrentTab,
metaKey,
mockRequest,
- e as expect
+ e as expecting
} from './support/test-utils'
-import { test } from '@playwright/test'
+import { test, expect } from '@playwright/test'
import { LOCAL_SERVER_ADDR } from './support/server'
const DEFAULT_CONFIG = {
@@ -25,7 +25,10 @@ async function openPage(page, config, options = {}) {
const configJson = JSON.stringify({ ...DEFAULT_CONFIG, ...config })
let path = `/plausible-main.html?script_config=${configJson}`
if (options.beforeScriptLoaded) {
- path += `&before_script_loaded=${options.beforeScriptLoaded}`
+ path += `&beforeScriptLoaded=${options.beforeScriptLoaded}`
+ }
+ if (options.skipPlausibleInit) {
+ path += `&skipPlausibleInit=1`
}
await page.goto(path)
await page.waitForFunction('window.plausible !== undefined')
@@ -40,12 +43,12 @@ test.describe('plausible-main.js', () => {
test('triggers pageview and engagement automatically', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => openPage(page, {}),
- expectedRequests: [{ n: 'pageview', d: 'example.com', u: expect.stringContaining('plausible-main.html')}]
+ expectedRequests: [{ n: 'pageview', d: 'example.com', u: expecting.stringContaining('plausible-main.html')}]
})
await expectPlausibleInAction(page, {
action: () => hideAndShowCurrentTab(page, {delay: 2000}),
- expectedRequests: [{n: 'engagement', d: 'example.com', u: expect.stringContaining('plausible-main.html')}],
+ expectedRequests: [{n: 'engagement', d: 'example.com', u: expecting.stringContaining('plausible-main.html')}],
})
})
@@ -57,14 +60,6 @@ test.describe('plausible-main.js', () => {
})
})
- test('supports overriding the endpoint with a custom proxy endpoint', async ({ page }) => {
- await expectPlausibleInAction(page, {
- pathToMock: 'http://proxy.io/endpoint',
- action: () => openPage(page, { endpoint: 'http://proxy.io/endpoint' }),
- expectedRequests: [{ n: 'pageview', d: 'example.com', u: expect.stringContaining('plausible-main.html')}]
- })
- })
-
test('does not track pageview props, outbound links, file downloads or tagged events without features being enabled', async ({ page }) => {
await expectPlausibleInAction(page, {
action: async () => {
@@ -73,7 +68,7 @@ test.describe('plausible-main.js', () => {
await page.click('#tagged-event')
await page.click('#outbound-link')
},
- expectedRequests: [{ n: 'pageview', p: expect.toBeUndefined() }],
+ expectedRequests: [{ n: 'pageview', p: expecting.toBeUndefined() }],
refutedRequests: [{ n: 'File Download' }, { n: 'Purchase' }, { n: 'Outbound Link: Click' }],
// Webkit captures engagement events differently, so we ignore them in this test
shouldIgnoreRequest: (payload) => payload.n === 'engagement'
@@ -87,8 +82,8 @@ test.describe('plausible-main.js', () => {
await page.click('#outbound-link')
},
expectedRequests: [
- { n: 'pageview', d: 'example.com', u: expect.stringContaining('plausible-main.html') },
- { n: 'Outbound Link: Click', d: 'example.com', u: expect.stringContaining('plausible-main.html'), p: { url: 'https://example.com/' } },
+ { n: 'pageview', d: 'example.com', u: expecting.stringContaining('plausible-main.html') },
+ { n: 'Outbound Link: Click', d: 'example.com', u: expecting.stringContaining('plausible-main.html'), p: { url: 'https://example.com/' } },
]
})
})
@@ -102,13 +97,76 @@ test.describe('plausible-main.js', () => {
})
})
- test('tracks pageview props (when feature enabled)', async ({ page }) => {
+ test('tracks static custom pageview properties (when feature enabled)', async ({ page }) => {
await expectPlausibleInAction(page, {
- action: () => openPage(page, { pageviewProps: true}),
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({ customProperties: { "some-prop": "456" } })
+ })
+ },
expectedRequests: [{ n: 'pageview', p: { "some-prop": "456" } }]
})
})
+ test('tracks dynamic custom pageview properties (when feature enabled)', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({ customProperties: () => ({ "title": document.title }) })
+ })
+ },
+ expectedRequests: [{ n: 'pageview', p: { "title": "plausible-main.js tests" } }]
+ })
+ })
+
+ test('tracks dynamic custom pageview properties with custom events and engagements', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({
+ customProperties: (eventName) => ({ "author": "Uku", "some-prop": "456", [eventName]: "1" })
+ })
+ })
+ await page.click('#custom-event')
+ await hideAndShowCurrentTab(page, { delay: 200 })
+ },
+ expectedRequests: [
+ { n: 'pageview', p: { "author": "Uku", "some-prop": "456", "pageview": "1"} },
+ // Passed property to `plausible` call overrides the default from `config.customProperties`
+ { n: 'Custom event', p: { "author": "Karl", "some-prop": "456", "Custom event": "1" } },
+ // Engagement event inherits props from the pageview event
+ { n: 'engagement', p: { "author": "Uku", "some-prop": "456", "pageview": "1"} },
+ ]
+ })
+ })
+
+ test('invalid function customProperties are ignored', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({ customProperties: () => document.title })
+ })
+ },
+ expectedRequests: [{ n: 'pageview', p: expecting.toBeUndefined() }]
+ })
+ })
+
+ test('invalid customProperties are ignored', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({ customProperties: "abcdef" })
+ })
+ },
+ expectedRequests: [{ n: 'pageview', p: expecting.toBeUndefined() }]
+ })
+ })
+
test('manual mode does not track pageviews', async ({ page }) => {
await expectPlausibleInAction(page, {
action: async () => {
@@ -137,7 +195,7 @@ test.describe('plausible-main.js', () => {
test('does not send `h` parameter when `hash` config is disabled', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => openPage(page, {}),
- expectedRequests: [{ n: 'pageview', h: expect.toBeUndefined() }]
+ expectedRequests: [{ n: 'pageview', h: expecting.toBeUndefined() }]
})
})
@@ -153,7 +211,7 @@ test.describe('plausible-main.js', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#tagged-event'),
- expectedRequests: [{ n: 'Purchase', p: { foo: 'bar' }, $: expect.toBeUndefined() }]
+ expectedRequests: [{ n: 'Purchase', p: { foo: 'bar' }, $: expecting.toBeUndefined() }]
})
})
@@ -172,4 +230,71 @@ test.describe('plausible-main.js', () => {
expectedRequests: [{ n: 'custom-event', p: { foo: 'bar' }, i: false }, { n: 'pageview' }]
})
})
+
+ test('handles double-initialization of the script with a console.warn', async ({ page }) => {
+ const consolePromise = page.waitForEvent('console')
+
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {})
+ await page.evaluate(() => {
+ window.plausible.init()
+ })
+ await consolePromise
+ },
+ expectedRequests: [{ n: 'pageview' }]
+ })
+
+ const warning = await consolePromise
+ expect(warning.type()).toBe("warning")
+ expect(warning.text()).toContain('Plausible analytics script was already initialized, skipping init')
+ })
+
+ test('handles the script being loaded and initialized multiple times', async ({ page }) => {
+ const consolePromise = page.waitForEvent('console')
+
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {})
+ await page.evaluate(() => {
+ window.includePlausibleScript()
+ })
+ await consolePromise
+ },
+ expectedRequests: [{ n: 'pageview' }]
+ })
+
+ const warning = await consolePromise
+ expect(warning.type()).toBe("warning")
+ expect(warning.text()).toContain('Plausible analytics script was already initialized, skipping init')
+ })
+
+ test('does not support overriding domain via `init`', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({
+ domain: 'another-domain.com'
+ })
+ })
+ },
+ expectedRequests: [{ n: 'pageview', d: 'example.com', u: expecting.stringContaining('plausible-main.html') }]
+ })
+ })
+
+ test('supports overriding the endpoint with a custom proxy via `init`', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ pathToMock: 'http://proxy.io/endpoint',
+ action: async () => {
+ await openPage(page, {}, { skipPlausibleInit: true })
+ await page.evaluate(() => {
+ plausible.init({
+ endpoint: 'http://proxy.io/endpoint'
+ })
+ })
+ },
+ expectedRequests: [{ n: 'pageview', d: 'example.com', u: expecting.stringContaining('plausible-main.html')}]
+ })
+ })
})
diff --git a/tracker/test/support/server.js b/tracker/test/support/server.js
index d07a976d21..fa3a9aac48 100644
--- a/tracker/test/support/server.js
+++ b/tracker/test/support/server.js
@@ -24,7 +24,7 @@ export function runLocalFileServer() {
let code = compileFile(variant, { returnCode: true })
if (name === 'plausible-main.js') {
- code = code.replace('"<%= @config_json %>"', req.query.script_config)
+ code = code.replace('"<%= @config_js %>"', req.query.script_config)
}
res.send(code)