Skip to content

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

Script v2: Apply prettier (#5718)

Artur Patacc5ca4b752ec
diff --git a/.github/workflows/node.yml b/.github/workflows/node.yml
index ab0485ca51..f6ec3b2dd4 100644
--- a/.github/workflows/node.yml
+++ b/.github/workflows/node.yml
@@ -32,5 +32,5 @@ jobs:
- run: npm run check-format --prefix ./assets
- run: npm run test --prefix ./assets
- run: npm run lint --prefix ./tracker
- # - run: npm run check-format --prefix ./tracker
+ - run: npm run check-format --prefix ./tracker
- run: npm run deploy --prefix ./tracker
diff --git a/tracker/ARCHITECTURE.md b/tracker/ARCHITECTURE.md
index f8bda549be..b1881d38a6 100644
--- a/tracker/ARCHITECTURE.md
+++ b/tracker/ARCHITECTURE.md
@@ -32,6 +32,7 @@ Plausible provides a web 'snippet' users can include on their site, tooling for
As Plausible doesn't have the workforce to maintain multiple code bases, everything is built from the same underlying source code.
This is achieved by:
+
- Having a canonical list of compiled variants in `tracker/compiler/variants.json`
- Using `COMPILE` globals to toggle certain functionality on/off depending on the variant.
- Having the script minifier drop dead branches of the code from each variant.
@@ -74,7 +75,7 @@ Contains source code to verify that the tracker script is installed correctly wi
### `tracker/compiler/variants.json`
-Contains a list of variants and associated global `COMPILE` flags.
+Contains a list of variants and associated global `COMPILE` flags.
- `manualVariants` are the main variants we need to care for, containing both the web snippet and npm package.
- `legacyVariants` is a list of all the legacy variants we support, generated by `tracker/compiler/generate-variants.js`
diff --git a/tracker/README.md b/tracker/README.md
index 37300740d9..d10f1f131c 100644
--- a/tracker/README.md
+++ b/tracker/README.md
@@ -25,6 +25,7 @@ Use `node compile.js --watch` to watch for changes.
Use `node compile.js --web-snippet` if you need to update web snippet code.
### Tests
+
Tests can be run in UI mode via `npm run playwright --ui`. This helps with debugging.
### NPM package
@@ -40,10 +41,12 @@ More instructions can be found in [yalc repo](https://github.com/wclr/yalc).
## Cloud deployment
Handled via PRs. When making tracker changes, it's required to:
+
- Tag your PR with a `tracker release:` label
- Update `tracker/CHANGELOG.md`
After merge github actions automatically:
+
- includes the updated tracker scripts in the next cloud deploy
- updates npm package package.json and CHANGELOG.md with the new version
- releases the new package version on NPM.
diff --git a/tracker/compile.js b/tracker/compile.js
index 591587f485..5c9a4527d7 100644
--- a/tracker/compile.js
+++ b/tracker/compile.js
@@ -4,19 +4,19 @@ import chokidar from 'chokidar'
const { values } = parseArgs({
options: {
- 'watch': {
+ watch: {
type: 'boolean',
short: 'w'
},
- 'help': {
- type: 'boolean',
+ help: {
+ type: 'boolean'
},
- 'suffix': {
+ suffix: {
type: 'string',
default: ''
},
'web-snippet': {
- type: 'boolean',
+ type: 'boolean'
}
}
})
@@ -24,11 +24,19 @@ const { values } = parseArgs({
if (values.help) {
console.log('Usage: node compile.js [flags]')
console.log('Options:')
- 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);
+ 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)
}
if (values['web-snippet']) {
diff --git a/tracker/compiler/analyze-sizes.js b/tracker/compiler/analyze-sizes.js
index 604a050925..8d214d66a4 100644
--- a/tracker/compiler/analyze-sizes.js
+++ b/tracker/compiler/analyze-sizes.js
@@ -23,18 +23,18 @@ import variantsFile from './variants.json' with { type: 'json' }
const { values } = parseArgs({
options: {
- 'help': {
- type: 'boolean',
+ help: {
+ type: 'boolean'
},
- 'currentSuffix': {
+ currentSuffix: {
type: 'string',
default: 'current'
},
- 'baselineSuffix': {
+ baselineSuffix: {
type: 'string',
default: 'master'
},
- 'usePreviousData': {
+ usePreviousData: {
type: 'boolean',
default: false
}
@@ -43,8 +43,8 @@ const { values } = parseArgs({
const { currentSuffix, baselineSuffix } = values
const __dirname = path.dirname(fileURLToPath(import.meta.url))
-const TRACKER_FILES_DIR = path.join(__dirname, "../../priv/tracker/js/")
-const NPM_PACKAGE_FILES_DIR = path.join(__dirname, "../npm_package")
+const TRACKER_FILES_DIR = path.join(__dirname, '../../priv/tracker/js/')
+const NPM_PACKAGE_FILES_DIR = path.join(__dirname, '../npm_package')
const HEADER = ['', 'Brotli', 'Gzip', 'Uncompressed']
@@ -52,22 +52,34 @@ if (values.help) {
console.log('Usage: node analyze-sizes.js master current')
console.log('Options:')
console.log(' --help Show this help message')
- console.log(' --currentSuffix The suffix of the current script variants (see suffix flag for compile.js). Default: current')
- console.log(' --baselineSuffix The suffix of the previous script variants (see suffix flag for compile.js). Default: master')
- console.log(' --usePreviousData Use data from a previous run, speeding up the analysis.')
- process.exit(0);
+ console.log(
+ ' --currentSuffix The suffix of the current script variants (see suffix flag for compile.js). Default: current'
+ )
+ console.log(
+ ' --baselineSuffix The suffix of the previous script variants (see suffix flag for compile.js). Default: master'
+ )
+ console.log(
+ ' --usePreviousData Use data from a previous run, speeding up the analysis.'
+ )
+ process.exit(0)
}
-
let fileData
if (values.usePreviousData) {
- fileData = JSON.parse(fs.readFileSync(path.join(__dirname, '.analyze-sizes.json'), 'utf8'))
+ fileData = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '.analyze-sizes.json'), 'utf8')
+ )
} else {
fileData = readPlausibleScriptSizes()
- fs.writeFileSync(path.join(__dirname, '.analyze-sizes.json'), JSON.stringify(fileData))
+ fs.writeFileSync(
+ path.join(__dirname, '.analyze-sizes.json'),
+ JSON.stringify(fileData)
+ )
}
-const manualVariants = variantsFile.manualVariants.map((variant) => `'${variant.name}'`).join(', ')
+const manualVariants = variantsFile.manualVariants
+ .map((variant) => `'${variant.name}'`)
+ .join(', ')
const ctes = `
WITH
array(${manualVariants}) as manual_variants,
@@ -99,21 +111,27 @@ WITH
)
`
-const mainVariantResults = clickhouseLocal(`
+const mainVariantResults = clickhouseLocal(
+ `
${ctes}
SELECT *
FROM data
WHERE not is_legacy_variant
ORDER BY variant
-`, fileData)
+`,
+ fileData
+)
-const legacyVariantResults = clickhouseLocal(`
+const legacyVariantResults = clickhouseLocal(
+ `
${ctes}
SELECT *
FROM data
WHERE is_legacy_variant AND has(important_variants, variant)
ORDER BY length(variant)
-`, fileData)
+`,
+ fileData
+)
const rowAsMap = `
map(
@@ -133,7 +151,8 @@ map(
)
`
-const [summary] = clickhouseLocal(`
+const [summary] = clickhouseLocal(
+ `
${ctes}
SELECT
count() AS total_variants,
@@ -168,26 +187,45 @@ const [summary] = clickhouseLocal(`
'brotli_increase_percentage', toString(median(brotli_increase_percentage))
) AS median_result
FROM data
-`, fileData)
+`,
+ fileData
+)
-console.log(`Analyzed ${summary.total_variants} tracker script variants for size changes.`)
-console.log(`The following tables summarize the results, with comparison with the baseline version in parentheses.\n`)
+console.log(
+ `Analyzed ${summary.total_variants} tracker script variants for size changes.`
+)
+console.log(
+ `The following tables summarize the results, with comparison with the baseline version in parentheses.\n`
+)
-console.log("Main variants:")
+console.log('Main variants:')
console.log(createMarkdownTable(mainVariantResults))
-console.log("\nImportant legacy variants:")
+console.log('\nImportant legacy variants:')
console.log(createMarkdownTable(legacyVariantResults))
-console.log("\nSummary:")
-console.log(createMarkdownTable([
- { ...summary.largest_variant, variant: `Largest variant (${summary.largest_variant.variant})`},
- { ...summary.max_increase_variant, variant: `Max change (${summary.max_increase_variant.variant})`},
- { ...summary.min_increase_variant, variant: `Min change (${summary.min_increase_variant.variant})`},
- summary.median_result
-]))
+console.log('\nSummary:')
+console.log(
+ createMarkdownTable([
+ {
+ ...summary.largest_variant,
+ variant: `Largest variant (${summary.largest_variant.variant})`
+ },
+ {
+ ...summary.max_increase_variant,
+ variant: `Max change (${summary.max_increase_variant.variant})`
+ },
+ {
+ ...summary.min_increase_variant,
+ variant: `Min change (${summary.min_increase_variant.variant})`
+ },
+ summary.median_result
+ ])
+)
-console.log(`\nIn total, ${summary.brotli_increase_percentaged_variants} variants brotli size increased and ${summary.brotli_decreased_variants} variants brotli size decreased.`)
+console.log(
+ `\nIn total, ${summary.brotli_increase_percentaged_variants} variants brotli size increased and ${summary.brotli_decreased_variants} variants brotli size decreased.`
+)
function createMarkdownTable(rows) {
return markdownTable([HEADER].concat(rows.map(markdownRow)))
@@ -208,7 +246,6 @@ function markdownRow(row) {
]
}
-
function sizeColumn(row, key) {
const currentSize = row[`current_${key}`]
const previousIncrease = row[`${key}_increase`]
@@ -230,11 +267,13 @@ function addSign(value) {
}
function readPlausibleScriptSizes() {
- const trackerFileSizes = fs.readdirSync(TRACKER_FILES_DIR)
+ const trackerFileSizes = fs
+ .readdirSync(TRACKER_FILES_DIR)
.filter(isRelevantFile)
.map((filename) => readFileSize(filename, TRACKER_FILES_DIR))
- const npmPackageFileSizes = fs.readdirSync(NPM_PACKAGE_FILES_DIR)
+ const npmPackageFileSizes = fs
+ .readdirSync(NPM_PACKAGE_FILES_DIR)
.filter(isRelevantFile)
.map((filename) => readFileSize(filename, NPM_PACKAGE_FILES_DIR))
@@ -246,7 +285,10 @@ function readFileSize(filename, basepath) {
const [_, variant, suffix] = /(.*)[.]js(.*)/.exec(filename)
return {
- variant: (basepath === TRACKER_FILES_DIR ? `${variant}.js` : 'npm_package/plausible.js'),
+ variant:
+ basepath === TRACKER_FILES_DIR
+ ? `${variant}.js`
+ : 'npm_package/plausible.js',
suffix,
uncompressed: fs.statSync(filePath).size,
gzip: execSync(`gzip -c -9 "${filePath}"`).length,
@@ -255,18 +297,23 @@ function readFileSize(filename, basepath) {
}
function isRelevantFile(filename) {
- return !['.gitkeep', 'p.js'].includes(filename) &&
+ return (
+ !['.gitkeep', 'p.js'].includes(filename) &&
filename.includes('.js') &&
(filename.includes(currentSuffix) || filename.includes(baselineSuffix))
+ )
}
function clickhouseLocal(sql, inputLines = null) {
const options = {}
if (inputLines) {
- options.input = inputLines.map(JSON.stringify).join("\n")
+ options.input = inputLines.map(JSON.stringify).join('\n')
}
- const result = execSync(`clickhouse-local --query="${sql}" --format=JSON ${inputLines ? "--input-format=JSONLines" : ""}`, options)
+ const result = execSync(
+ `clickhouse-local --query="${sql}" --format=JSON ${inputLines ? '--input-format=JSONLines' : ''}`,
+ options
+ )
const json = JSON.parse(result.toString())
return json.data
diff --git a/tracker/compiler/can-skip-compile.js b/tracker/compiler/can-skip-compile.js
index b6f90b8885..b2d47b7f35 100644
--- a/tracker/compiler/can-skip-compile.js
+++ b/tracker/compiler/can-skip-compile.js
@@ -15,19 +15,19 @@ const COMPILE_DEPENDENCIES = [
]
function currentHash() {
- const combinedHash = crypto.createHash('sha256');
+ const combinedHash = crypto.createHash('sha256')
for (const filePath of COMPILE_DEPENDENCIES) {
try {
- const fileContent = fs.readFileSync(filePath);
- const fileHash = crypto.createHash('sha256').update(fileContent).digest();
- combinedHash.update(fileHash);
+ const fileContent = fs.readFileSync(filePath)
+ const fileHash = crypto.createHash('sha256').update(fileContent).digest()
+ combinedHash.update(fileHash)
} catch (error) {
- throw new Error(`Failed to read or hash ${filePath}: ${error.message}`);
+ throw new Error(`Failed to read or hash ${filePath}: ${error.message}`)
}
}
- return combinedHash.digest('hex');
+ return combinedHash.digest('hex')
}
function lastHash() {
diff --git a/tracker/compiler/generate-variants.js b/tracker/compiler/generate-variants.js
index b9e9a686eb..e68f7a8c71 100644
--- a/tracker/compiler/generate-variants.js
+++ b/tracker/compiler/generate-variants.js
@@ -9,13 +9,25 @@ function idToGlobal(id) {
return `COMPILE_${id.replace('-', '_').toUpperCase()}`
}
-const LEGACY_VARIANT_NAMES = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue"]
+const LEGACY_VARIANT_NAMES = [
+ 'hash',
+ 'outbound-links',
+ 'exclusions',
+ 'compat',
+ 'local',
+ 'manual',
+ 'file-downloads',
+ 'pageview-props',
+ 'tagged-events',
+ 'revenue'
+]
let legacyVariants = [...g.clone.powerSet(LEGACY_VARIANT_NAMES)]
- .map(a => a.sort())
+ .map((a) => a.sort())
.map((variant) => ({
- name: variant.length > 0 ? `plausible.${variant.join('.')}.js` : 'plausible.js',
+ name:
+ variant.length > 0 ? `plausible.${variant.join('.')}.js` : 'plausible.js',
globals: {
- ...Object.fromEntries(variant.map(id => [idToGlobal(id), true])),
+ ...Object.fromEntries(variant.map((id) => [idToGlobal(id), true])),
COMPILE_PLAUSIBLE_LEGACY_VARIANT: true
}
}))
@@ -23,4 +35,7 @@ let legacyVariants = [...g.clone.powerSet(LEGACY_VARIANT_NAMES)]
const variantsFile = path.join(__dirname, 'variants.json')
const existingData = JSON.parse(fs.readFileSync(variantsFile, 'utf8'))
-fs.writeFileSync(variantsFile, JSON.stringify({ ...existingData, legacyVariants }, null, 2) + "\n")
+fs.writeFileSync(
+ variantsFile,
+ JSON.stringify({ ...existingData, legacyVariants }, null, 2) + '\n'
+)
diff --git a/tracker/compiler/index.js b/tracker/compiler/index.js
index 708b1ad135..7a7c67f53d 100644
--- a/tracker/compiler/index.js
+++ b/tracker/compiler/index.js
@@ -7,7 +7,7 @@ import variantsFile from './variants.json' with { type: 'json' }
import { canSkipCompile } from './can-skip-compile.js'
import packageJson from '../package.json' with { type: 'json' }
import progress from 'cli-progress'
-import { spawn, Worker, Pool } from "threads"
+import { spawn, Worker, Pool } from 'threads'
import json from '@rollup/plugin-json'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -28,27 +28,34 @@ export const DEFAULT_GLOBALS = {
COMPILE_TAGGED_EVENTS: false,
COMPILE_REVENUE: false,
COMPILE_EXCLUSIONS: false,
- COMPILE_TRACKER_SCRIPT_VERSION: packageJson.tracker_script_version,
+ COMPILE_TRACKER_SCRIPT_VERSION: packageJson.tracker_script_version
}
-const ALL_VARIANTS = variantsFile.legacyVariants.concat(variantsFile.manualVariants)
+const ALL_VARIANTS = variantsFile.legacyVariants.concat(
+ variantsFile.manualVariants
+)
export async function compileAll(options = {}) {
if (process.env.NODE_ENV === 'dev' && canSkipCompile()) {
- console.info('COMPILATION SKIPPED: No changes detected in tracker dependencies')
+ console.info(
+ 'COMPILATION SKIPPED: No changes detected in tracker dependencies'
+ )
return
}
const bundledCode = await bundleCode()
- const startTime = Date.now();
+ const startTime = Date.now()
console.log(`Starting compilation of ${ALL_VARIANTS.length} variants...`)
- const bar = new progress.SingleBar({ clearOnComplete: true }, progress.Presets.shades_classic)
+ const bar = new progress.SingleBar(
+ { clearOnComplete: true },
+ progress.Presets.shades_classic
+ )
bar.start(ALL_VARIANTS.length, 0)
const workerPool = Pool(() => spawn(new Worker('./worker-thread.js')))
- ALL_VARIANTS.forEach(variant => {
+ ALL_VARIANTS.forEach((variant) => {
workerPool.queue(async (worker) => {
await worker.compileFile(variant, { ...options, bundledCode })
bar.increment()
@@ -59,7 +66,9 @@ export async function compileAll(options = {}) {
await workerPool.terminate()
bar.stop()
- console.log(`Completed compilation of ${ALL_VARIANTS.length} variants in ${((Date.now() - startTime) / 1000).toFixed(2)}s`);
+ console.log(
+ `Completed compilation of ${ALL_VARIANTS.length} variants in ${((Date.now() - startTime) / 1000).toFixed(2)}s`
+ )
}
export async function compileFile(variant, options) {
@@ -69,7 +78,7 @@ export async function compileFile(variant, options) {
if (variant.entry_point) {
code = await bundleCode(variant.entry_point)
} else {
- code = options.bundledCode || await bundleCode()
+ code = options.bundledCode || (await bundleCode())
}
if (!variant.npm_package) {
@@ -111,7 +120,7 @@ export function compileWebSnippet() {
async function bundleCode(entryPoint = 'src/plausible.js') {
const bundle = await rollup({
input: entryPoint,
- plugins: [json({compact: true})]
+ plugins: [json({ compact: true })]
})
const { output } = await bundle.generate({ format: 'esm' })
@@ -121,11 +130,13 @@ async function bundleCode(entryPoint = 'src/plausible.js') {
function outputPath(variant, options) {
if (variant.output_path) {
- return relPath(`../../${variant.output_path}${options.suffix || ""}`)
+ return relPath(`../../${variant.output_path}${options.suffix || ''}`)
} else if (variant.npm_package) {
- return relPath(`../${variant.name}${options.suffix || ""}`)
+ return relPath(`../${variant.name}${options.suffix || ''}`)
} else {
- return relPath(`../../priv/tracker/js/${variant.name}${options.suffix || ""}`)
+ return relPath(
+ `../../priv/tracker/js/${variant.name}${options.suffix || ''}`
+ )
}
}
diff --git a/tracker/compiler/worker-thread.js b/tracker/compiler/worker-thread.js
index a0a7c123c4..fdd339f867 100644
--- a/tracker/compiler/worker-thread.js
+++ b/tracker/compiler/worker-thread.js
@@ -1,4 +1,4 @@
import { compileFile } from './index.js'
-import { expose } from "threads/worker"
+import { expose } from 'threads/worker'
expose({ compileFile })
diff --git a/tracker/installation_support/autoconsent-rules/autoconsent/cookiebot.json b/tracker/installation_support/autoconsent-rules/autoconsent/cookiebot.json
index 8391511022..a6c714e9a2 100644
--- a/tracker/installation_support/autoconsent-rules/autoconsent/cookiebot.json
+++ b/tracker/installation_support/autoconsent-rules/autoconsent/cookiebot.json
@@ -1,9 +1,21 @@
{
- "name": "cookiebot",
- "prehideSelectors": [],
- "detectCmp": [{ "exists": "#CybotCookiebotDialogBodyButtonAccept, #CybotCookiebotDialogBody, #CybotCookiebotDialogBodyLevelButtonPreferences, #cb-cookieoverlay, #CybotCookiebotDialog" }],
- "detectPopup": [{ "visible": "#CybotCookiebotDialogBodyButtonAccept, #CybotCookiebotDialogBody, #CybotCookiebotDialogBodyLevelButtonPreferences, #cb-cookieoverlay, #CybotCookiebotDialog, #cookiebanner" }],
- "optIn": [{ "waitForThenClick": "#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll" }],
- "optOut": [],
- "test": []
+ "name": "cookiebot",
+ "prehideSelectors": [],
+ "detectCmp": [
+ {
+ "exists": "#CybotCookiebotDialogBodyButtonAccept, #CybotCookiebotDialogBody, #CybotCookiebotDialogBodyLevelButtonPreferences, #cb-cookieoverlay, #CybotCookiebotDialog"
+ }
+ ],
+ "detectPopup": [
+ {
+ "visible": "#CybotCookiebotDialogBodyButtonAccept, #CybotCookiebotDialogBody, #CybotCookiebotDialogBodyLevelButtonPreferences, #cb-cookieoverlay, #CybotCookiebotDialog, #cookiebanner"
+ }
+ ],
+ "optIn": [
+ {
+ "waitForThenClick": "#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll"
+ }
+ ],
+ "optOut": [],
+ "test": []
}
diff --git a/tracker/installation_support/check-cookie-banner.js b/tracker/installation_support/check-cookie-banner.js
index bedf054253..7510c1e951 100644
--- a/tracker/installation_support/check-cookie-banner.js
+++ b/tracker/installation_support/check-cookie-banner.js
@@ -9,18 +9,18 @@ const SELECTORS = {
'#CybotCookiebotDialogBodyLevelButtonPreferences',
'#cb-cookieoverlay',
'#CybotCookiebotDialog',
- '#cookiebanner',
+ '#cookiebanner'
]
}
function isVisible(element) {
- const style = window.getComputedStyle(element);
+ const style = window.getComputedStyle(element)
return (
style.display !== 'none' &&
style.visibility !== 'hidden' &&
element.offsetParent !== null
- );
+ )
}
export function checkCookieBanner() {
@@ -35,4 +35,4 @@ export function checkCookieBanner() {
}
return false
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/check-data-domain-mismatch.js b/tracker/installation_support/check-data-domain-mismatch.js
index a370c55c4d..f89cfb84b5 100644
--- a/tracker/installation_support/check-data-domain-mismatch.js
+++ b/tracker/installation_support/check-data-domain-mismatch.js
@@ -1,12 +1,14 @@
export function checkDataDomainMismatch(snippets, expectedDataDomain) {
if (!snippets || snippets.length === 0) return false
- return snippets.some(snippet => {
+ return snippets.some((snippet) => {
const scriptDataDomain = snippet.getAttribute('data-domain')
- const multiple = scriptDataDomain.split(',').map(d => d.trim())
- const dataDomainMismatch = !multiple.some((domain) => domain.replace(/^www\./, '') === expectedDataDomain)
-
+ const multiple = scriptDataDomain.split(',').map((d) => d.trim())
+ const dataDomainMismatch = !multiple.some(
+ (domain) => domain.replace(/^www\./, '') === expectedDataDomain
+ )
+
return dataDomainMismatch
})
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/check-gtm.js b/tracker/installation_support/check-gtm.js
index cc91b00a78..b82e616d34 100644
--- a/tracker/installation_support/check-gtm.js
+++ b/tracker/installation_support/check-gtm.js
@@ -1,10 +1,8 @@
-const GTM_SIGNATURES = [
- 'googletagmanager.com/gtm.js'
-]
+const GTM_SIGNATURES = ['googletagmanager.com/gtm.js']
function scanGTM(html) {
if (typeof html === 'string') {
- return GTM_SIGNATURES.some(signature => {
+ return GTM_SIGNATURES.some((signature) => {
return html.includes(signature)
})
}
@@ -18,4 +16,4 @@ export function checkGTM(document) {
}
return false
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/check-manual-extension.js b/tracker/installation_support/check-manual-extension.js
index 8060e59d8f..df1a945132 100644
--- a/tracker/installation_support/check-manual-extension.js
+++ b/tracker/installation_support/check-manual-extension.js
@@ -1,7 +1,7 @@
export function checkManualExtension(snippets) {
if (!snippets || snippets.length === 0) return false
- return snippets.some(snippet => {
+ return snippets.some((snippet) => {
return snippet.getAttribute('src').includes('manual.')
})
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/check-proxy-likely.js b/tracker/installation_support/check-proxy-likely.js
index c086634f33..df14e106e5 100644
--- a/tracker/installation_support/check-proxy-likely.js
+++ b/tracker/installation_support/check-proxy-likely.js
@@ -1,8 +1,8 @@
export function checkProxyLikely(snippets) {
if (!snippets || snippets.length === 0) return false
- return snippets.some(snippet => {
+ return snippets.some((snippet) => {
const src = snippet.getAttribute('src')
return src && !/^https:\/\/plausible\.io\//.test(src)
})
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/check-unknown-attributes.js b/tracker/installation_support/check-unknown-attributes.js
index 3e5a4bb161..06a6ab6ef8 100644
--- a/tracker/installation_support/check-unknown-attributes.js
+++ b/tracker/installation_support/check-unknown-attributes.js
@@ -12,7 +12,7 @@ const KNOWN_ATTRIBUTES = [
export function checkUnknownAttributes(snippets) {
if (!snippets || snippets.length === 0) return false
- return snippets.some(snippet => {
+ return snippets.some((snippet) => {
const attributes = snippet.attributes
for (let i = 0; i < attributes.length; i++) {
diff --git a/tracker/installation_support/check-wordpress.js b/tracker/installation_support/check-wordpress.js
index bba815e7ec..09da51a3d7 100644
--- a/tracker/installation_support/check-wordpress.js
+++ b/tracker/installation_support/check-wordpress.js
@@ -1,10 +1,7 @@
-export const WORDPRESS_PLUGIN_VERSION_SELECTOR = 'meta[name="plausible-analytics-version"]'
+export const WORDPRESS_PLUGIN_VERSION_SELECTOR =
+ 'meta[name="plausible-analytics-version"]'
-const WORDPRESS_SIGNATURES = [
- 'wp-content',
- 'wp-includes',
- 'wp-json'
-]
+const WORDPRESS_SIGNATURES = ['wp-content', 'wp-includes', 'wp-json']
function scanWpPlugin(document) {
if (typeof document.querySelector === 'function') {
@@ -17,9 +14,9 @@ function scanWpPlugin(document) {
function scanWp(html) {
if (typeof html === 'string') {
- return WORDPRESS_SIGNATURES.some(signature => {
+ return WORDPRESS_SIGNATURES.some((signature) => {
return html.includes(signature)
- })
+ })
}
return false
@@ -28,10 +25,11 @@ function scanWp(html) {
export function checkWordPress(document) {
if (typeof document === 'object') {
const wordpressPlugin = scanWpPlugin(document)
- const wordpressLikely = wordpressPlugin || scanWp(document.documentElement?.outerHTML)
-
- return {wordpressPlugin, wordpressLikely}
+ const wordpressLikely =
+ wordpressPlugin || scanWp(document.documentElement?.outerHTML)
+
+ return { wordpressPlugin, wordpressLikely }
}
- return {wordpressPlugin: false, wordpressLikely: false}
-}
\ No newline at end of file
+ return { wordpressPlugin: false, wordpressLikely: false }
+}
diff --git a/tracker/installation_support/detector.js b/tracker/installation_support/detector.js
index 570e1cc6e3..9fe7865ee1 100644
--- a/tracker/installation_support/detector.js
+++ b/tracker/installation_support/detector.js
@@ -1,9 +1,13 @@
-import { waitForPlausibleFunction } from "./plausible-function-check"
-import { checkWordPress } from "./check-wordpress"
-import { checkGTM } from "./check-gtm"
-import { checkNPM } from "./check-npm"
+import { waitForPlausibleFunction } from './plausible-function-check'
+import { checkWordPress } from './check-wordpress'
+import { checkGTM } from './check-gtm'
+import { checkNPM } from './check-npm'
-window.scanPageBeforePlausibleInstallation = async function({ detectV1, debug, timeoutMs }) {
+window.scanPageBeforePlausibleInstallation = async function ({
+ detectV1,
+ debug,
+ timeoutMs
+}) {
function log(message) {
if (debug) console.log('[Plausible Verification]', message)
}
@@ -18,7 +22,7 @@ window.scanPageBeforePlausibleInstallation = async function({ detectV1, debug, t
log(`v1Detected: ${v1Detected}`)
}
- const {wordpressPlugin, wordpressLikely} = checkWordPress(document)
+ const { wordpressPlugin, wordpressLikely } = checkWordPress(document)
log(`wordpressPlugin: ${wordpressPlugin}`)
log(`wordpressLikely: ${wordpressLikely}`)
diff --git a/tracker/installation_support/plausible-function-check.js b/tracker/installation_support/plausible-function-check.js
index 8bcba533da..d7ae65a00a 100644
--- a/tracker/installation_support/plausible-function-check.js
+++ b/tracker/installation_support/plausible-function-check.js
@@ -1,9 +1,9 @@
-import { runThrottledCheck } from "./run-check"
+import { runThrottledCheck } from './run-check'
export async function plausibleFunctionCheck(log) {
log('Checking for Plausible function...')
const plausibleFound = await waitForPlausibleFunction()
-
+
if (plausibleFound) {
log('Plausible function found. Executing test event...')
const callbackResult = await testPlausibleCallback(log)
@@ -11,17 +11,21 @@ export async function plausibleFunctionCheck(log) {
return { plausibleInstalled: true, callbackStatus: callbackResult.status }
} else {
log('Plausible function not found')
- return { plausibleInstalled: false}
+ return { plausibleInstalled: false }
}
}
export async function waitForPlausibleFunction(timeout = 5000) {
const checkFn = (opts) => {
- if (window.plausible?.l) { return true }
- if (opts.timeout) { return false }
+ if (window.plausible?.l) {
+ return true
+ }
+ if (opts.timeout) {
+ return false
+ }
return 'continue'
}
- return await runThrottledCheck(checkFn, {timeout: timeout, interval: 100})
+ return await runThrottledCheck(checkFn, { timeout: timeout, interval: 100 })
}
function testPlausibleCallback(log) {
@@ -38,11 +42,11 @@ function testPlausibleCallback(log) {
try {
window.plausible('verification-agent-test', {
- callback: function(options) {
+ callback: function (options) {
if (!callbackResolved) {
callbackResolved = true
clearTimeout(callbackTimeout)
- resolve({status: options && options.status ? options.status : -1 })
+ resolve({ status: options && options.status ? options.status : -1 })
}
}
})
@@ -55,4 +59,4 @@ function testPlausibleCallback(log) {
}
}
})
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/run-check.js b/tracker/installation_support/run-check.js
index c9218e147d..eb2e892750 100644
--- a/tracker/installation_support/run-check.js
+++ b/tracker/installation_support/run-check.js
@@ -1,17 +1,17 @@
-export async function runThrottledCheck(checkFn, {timeout, interval}) {
+export async function runThrottledCheck(checkFn, { timeout, interval }) {
return runCheckRecursive(checkFn, timeout, interval, 1)
}
async function runCheckRecursive(checkFn, timeout, interval, iteration) {
return new Promise((resolve) => {
if (iteration * interval >= timeout) {
- resolve(checkFn({timeout: true}))
- } else if (checkFn({timeout: false}) !== 'continue') {
- resolve(checkFn({timeout: false}))
+ resolve(checkFn({ timeout: true }))
+ } else if (checkFn({ timeout: false }) !== 'continue') {
+ resolve(checkFn({ timeout: false }))
} else {
setTimeout(() => {
resolve(runCheckRecursive(checkFn, timeout, interval, iteration + 1))
}, interval)
}
})
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/snippet-checks.js b/tracker/installation_support/snippet-checks.js
index 8807f30d1c..c667b8f51d 100644
--- a/tracker/installation_support/snippet-checks.js
+++ b/tracker/installation_support/snippet-checks.js
@@ -1,4 +1,4 @@
-import { runThrottledCheck } from "./run-check"
+import { runThrottledCheck } from './run-check'
export async function waitForSnippetsV1(log) {
log('Starting snippet detection...')
@@ -6,19 +6,23 @@ export async function waitForSnippetsV1(log) {
let snippetCounts = await waitForFirstSnippet()
if (snippetCounts.all > 0) {
- log(`Found snippets: head=${snippetCounts.head}; body=${snippetCounts.body}`)
+ log(
+ `Found snippets: head=${snippetCounts.head}; body=${snippetCounts.body}`
+ )
log('Waiting for additional snippets to appear...')
snippetCounts = await waitForAdditionalSnippets()
- log(`Final snippet count: head=${snippetCounts.head}; body=${snippetCounts.body}`)
+ log(
+ `Final snippet count: head=${snippetCounts.head}; body=${snippetCounts.body}`
+ )
} else {
- log('No snippets found after 5 seconds')
+ log('No snippets found after 5 seconds')
}
return {
nodes: [...getHeadSnippets(), ...getBodySnippets()],
- counts: snippetCounts,
+ counts: snippetCounts
}
}
@@ -33,7 +37,7 @@ function getBodySnippets() {
function countSnippets() {
const headSnippets = getHeadSnippets()
const bodySnippets = getBodySnippets()
-
+
return {
head: headSnippets.length,
body: bodySnippets.length,
@@ -44,7 +48,7 @@ function countSnippets() {
async function waitForFirstSnippet() {
const checkFn = (opts) => {
const snippetsFound = countSnippets()
-
+
if (snippetsFound.all > 0 || opts.timeout) {
return snippetsFound
}
@@ -52,7 +56,7 @@ async function waitForFirstSnippet() {
return 'continue'
}
- return await runThrottledCheck(checkFn, {timeout: 5000, interval: 100})
+ return await runThrottledCheck(checkFn, { timeout: 5000, interval: 100 })
}
async function waitForAdditionalSnippets() {
@@ -61,4 +65,4 @@ async function waitForAdditionalSnippets() {
resolve(countSnippets())
}, 1000)
})
-}
\ No newline at end of file
+}
diff --git a/tracker/installation_support/verifier-v1.js b/tracker/installation_support/verifier-v1.js
index 2b59066dd6..aa40a46f75 100644
--- a/tracker/installation_support/verifier-v1.js
+++ b/tracker/installation_support/verifier-v1.js
@@ -1,14 +1,17 @@
-import { waitForSnippetsV1 } from "./snippet-checks"
-import { plausibleFunctionCheck } from "./plausible-function-check"
-import { checkDataDomainMismatch } from "./check-data-domain-mismatch"
-import { checkProxyLikely } from "./check-proxy-likely"
-import { checkWordPress } from "./check-wordpress"
-import { checkGTM } from "./check-gtm"
-import { checkCookieBanner } from "./check-cookie-banner"
-import { checkManualExtension } from "./check-manual-extension"
-import { checkUnknownAttributes } from "./check-unknown-attributes"
+import { waitForSnippetsV1 } from './snippet-checks'
+import { plausibleFunctionCheck } from './plausible-function-check'
+import { checkDataDomainMismatch } from './check-data-domain-mismatch'
+import { checkProxyLikely } from './check-proxy-likely'
+import { checkWordPress } from './check-wordpress'
+import { checkGTM } from './check-gtm'
+import { checkCookieBanner } from './check-cookie-banner'
+import { checkManualExtension } from './check-manual-extension'
+import { checkUnknownAttributes } from './check-unknown-attributes'
-window.verifyPlausibleInstallation = async function(expectedDataDomain, debug) {
+window.verifyPlausibleInstallation = async function (
+ expectedDataDomain,
+ debug
+) {
function log(message) {
if (debug) console.log('[Plausible Verification]', message)
}
@@ -21,7 +24,10 @@ window.verifyPlausibleInstallation = async function(expectedDataDomain, debug) {
const plausibleInstalled = plausibleFunctionDiagnostics.plausibleInstalled
const callbackStatus = plausibleFunctionDiagnostics.callbackStatus || 0
- const dataDomainMismatch = checkDataDomainMismatch(snippetData.nodes, expectedDataDomain)
+ const dataDomainMismatch = checkDataDomainMismatch(
+ snippetData.nodes,
+ expectedDataDomain
+ )
log(`dataDomainMismatch: ${dataDomainMismatch}`)
const manualScriptExtension = checkManualExtension(snippetData.nodes)
@@ -33,7 +39,7 @@ window.verifyPlausibleInstallation = async function(expectedDataDomain, debug) {
const proxyLikely = checkProxyLikely(snippetData.nodes)
log(`proxyLikely: ${proxyLikely}`)
- const {wordpressPlugin, wordpressLikely} = checkWordPress(document)
+ const { wordpressPlugin, wordpressLikely } = checkWordPress(document)
log(`wordpressPlugin: ${wordpressPlugin}`)
log(`wordpressLikely: ${wordpressLikely}`)
@@ -67,4 +73,4 @@ window.verifyPlausibleInstallation = async function(expectedDataDomain, debug) {
unknownAttributes: unknownAttributes
}
}
-}
\ No newline at end of file
+}
diff --git a/tracker/npm_package/CHANGELOG.md b/tracker/npm_package/CHANGELOG.md
index a6c6d3cd4d..8f4a87669d 100644
--- a/tracker/npm_package/CHANGELOG.md
+++ b/tracker/npm_package/CHANGELOG.md
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
+- Fix formatting issues.
+
## [0.4.2] - 2025-09-04
- Remove redeclared variables from the tracker.
diff --git a/tracker/npm_package/README.md b/tracker/npm_package/README.md
index 5077c2c228..86ead91626 100644
--- a/tracker/npm_package/README.md
+++ b/tracker/npm_package/README.md
@@ -6,6 +6,7 @@
Add [Plausible Analytics](https://plausible.io/) to your website.
## Features
+
- Small package size
- Same features and codebase as the official script, but as an NPM module
- Automatically track page views in your SPA apps
@@ -39,20 +40,20 @@ init({
See also [plausible.d.ts](https://github.com/plausible/analytics/blob/master/tracker/npm_package/plausible.d.ts) for typescript types.
-| Option | Description | Default |
-| --- | --- | --- |
-| `domain` | **Required** Your site's domain, as declared by you in Plausible's settings. | |
-| `endpoint` | The URL of the Plausible API endpoint. See proxying guide at https://plausible.io/docs/proxy/introduction | `"https://plausible.io/api/event"` |
-| `autoCapturePageviews` | Whether to automatically capture pageviews. | `true` |
-| `hashBasedRouting` | Whether the page uses hash based routing. Read more at https://plausible.io/docs/hash-based-routing | `false` |
-| `outboundLinks` | Whether to track outbound link clicks. | `false` |
-| `fileDownloads` | Whether to track file downloads. | `false` |
-| `formSubmissions` | Whether to track form submissions. | `false` |
-| `captureOnLocalhost` | Whether to capture events on localhost. | `false` |
-| `logging` | Whether to log on ignored events. | `true` |
-| `customProperties` | Object or function that returns custom properties for a given event. | `{}` |
-| `transformRequest` | Function that allows transforming or ignoring requests | |
-| `bindToWindow` | Binds `track` to `window.plausible` which is used by Plausible installation verification tool to detect whether Plausible has been installed correctly. If `bindToWindow` is set to false, the installation verification tool won't be able to automatically detect it on your site. | `true` |
+| Option | Description | Default |
+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- |
+| `domain` | **Required** Your site's domain, as declared by you in Plausible's settings. | |
+| `endpoint` | The URL of the Plausible API endpoint. See proxying guide at https://plausible.io/docs/proxy/introduction | `"https://plausible.io/api/event"` |
+| `autoCapturePageviews` | Whether to automatically capture pageviews. | `true` |
+| `hashBasedRouting` | Whether the page uses hash based routing. Read more at https://plausible.io/docs/hash-based-routing | `false` |
+| `outboundLinks` | Whether to track outbound link clicks. | `false` |
+| `fileDownloads` | Whether to track file downloads. | `false` |
+| `formSubmissions` | Whether to track form submissions. | `false` |
+| `captureOnLocalhost` | Whether to capture events on localhost. | `false` |
+| `logging` | Whether to log on ignored events. | `true` |
+| `customProperties` | Object or function that returns custom properties for a given event. | `{}` |
+| `transformRequest` | Function that allows transforming or ignoring requests | |
+| `bindToWindow` | Binds `track` to `window.plausible` which is used by Plausible installation verification tool to detect whether Plausible has been installed correctly. If `bindToWindow` is set to false, the installation verification tool won't be able to automatically detect it on your site. | `true` |
#### Using `customProperties`
@@ -61,7 +62,7 @@ To track a custom property with every page view, you can use the `customProperti
```javascript
init({
domain: 'my-app.com',
- customProperties: { "content_category": "news" }
+ customProperties: { content_category: 'news' }
})
```
@@ -70,7 +71,7 @@ init({
```javascript
init({
domain: 'my-app.com',
- customProperties: (eventName) => ({ "title": document.title })
+ customProperties: (eventName) => ({ title: document.title })
})
```
@@ -81,7 +82,7 @@ To track a custom event, call `track` and give it the name of the event. Custom
```javascript
import { track } from '@plausible-analytics/tracker'
-track('signup', { props: { tier: "startup" } })
+track('signup', { props: { tier: 'startup' } })
```
To mark an event as non-interactive so it would not be counted towards bounce rate calculations, set `interactive` option:
@@ -112,11 +113,11 @@ import { track } from '@plausible-analytics/tracker'
track('some-event', {
callback: (result) => {
if (result?.status) {
- console.debug("Request to plausible done. Status:", result.status)
+ console.debug('Request to plausible done. Status:', result.status)
} else if (result?.error) {
- console.log("Error handling request:", result.error)
+ console.log('Error handling request:', result.error)
} else {
- console.log("Request was ignored")
+ console.log('Request was ignored')
}
}
})
diff --git a/tracker/npm_package/plausible.d.ts b/tracker/npm_package/plausible.d.ts
index 5277f971e8..440c6b993e 100644
--- a/tracker/npm_package/plausible.d.ts
+++ b/tracker/npm_package/plausible.d.ts
@@ -6,7 +6,7 @@ export function track(eventName: string, options: PlausibleEventOptions): void
export interface PlausibleConfig {
// Your site's domain, as declared by you in Plausible's settings.
- domain: string,
+ domain: string
// The URL of the Plausible API endpoint. Defaults to https://plausible.io/api/event
// See proxying guide at https://plausible.io/docs/proxy/introduction
@@ -36,14 +36,18 @@ export interface PlausibleConfig {
// Custom properties to add to all events tracked.
// If passed as a function, it will be called when `track` is called.
- customProperties?: CustomProperties | ((eventName: string) => CustomProperties)
+ customProperties?:
+ | CustomProperties
+ | ((eventName: string) => CustomProperties)
// A function that can be used to transform the payload before it is sent to the API.
// If the function returns null or any other falsy value, the event will be ignored.
//
// This can be used to avoid sending certain types of events, or modifying any event
// parameters, e.g. to clean URLs of values that should not be recorded.
- transformRequest?: (payload: PlausibleRequestPayload) => PlausibleRequestPayload | null
+ transformRequest?: (
+ payload: PlausibleRequestPayload
+ ) => PlausibleRequestPayload | null
// If enabled (the default), the script will set `window.plausible` after `init` is called.
// This is used by the verifier to detect if the script is loaded from npm package.
@@ -67,7 +71,9 @@ export interface PlausibleEventOptions {
// When request is ignored, the result will be undefined.
// When request was delivered, the result will be an object with the response status code of the request.
// When there was a network error, the result will be an object with the error object.
- callback?: (result?: { status: number } | { error: unknown } | undefined) => void
+ callback?: (
+ result?: { status: number } | { error: unknown } | undefined
+ ) => void
// Overrides the URL of the page that the event is being tracked on.
// If not provided, `location.href` will be used.
@@ -78,26 +84,26 @@ export type CustomProperties = Record<string, string>
export type PlausibleEventRevenue = {
// Revenue amount in `currency`
- amount: number | string,
+ amount: number | string
// Currency is an ISO 4217 string representing the currency code, e.g. "USD" or "EUR"
currency: string
}
export type PlausibleRequestPayload = {
// Event name
- n: string,
+ n: string
// URL of the event
- u: string,
+ u: string
// Domain of the event
- d: string,
+ d: string
// Referrer
- r?: string | null,
+ r?: string | null
// Custom properties
- p?: CustomProperties,
+ p?: CustomProperties
// Revenue information
- $?: PlausibleEventRevenue,
+ $?: PlausibleEventRevenue
// Whether the event is interactive
- i?: boolean,
+ i?: boolean
} & Record<string, unknown>
// Default file types that are tracked when `fileDownloads` is enabled.
diff --git a/tracker/package.json b/tracker/package.json
index 68e9a5768c..7d071a14f7 100644
--- a/tracker/package.json
+++ b/tracker/package.json
@@ -1,5 +1,5 @@
{
- "tracker_script_version": 31,
+ "tracker_script_version": 32,
"type": "module",
"scripts": {
"lint": "eslint",
diff --git a/tracker/src/autocapture.js b/tracker/src/autocapture.js
index 6a7d2aee27..2d69a99704 100644
--- a/tracker/src/autocapture.js
+++ b/tracker/src/autocapture.js
@@ -1,18 +1,20 @@
import { config } from './config'
export function init(track) {
- var lastPage;
+ var lastPage
function page(isSPANavigation) {
if (!(COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting))) {
- if (isSPANavigation && lastPage === location.pathname) return;
+ if (isSPANavigation && lastPage === location.pathname) return
}
lastPage = location.pathname
track('pageview')
}
- var onSPANavigation = function () { page(true) }
+ var onSPANavigation = function () {
+ page(true)
+ }
if (COMPILE_HASH && (!COMPILE_CONFIG || config.hashBasedRouting)) {
window.addEventListener('hashchange', onSPANavigation)
@@ -22,7 +24,7 @@ export function init(track) {
var originalPushState = his['pushState']
his.pushState = function () {
originalPushState.apply(this, arguments)
- onSPANavigation();
+ onSPANavigation()
}
window.addEventListener('popstate', onSPANavigation)
}
@@ -34,8 +36,11 @@ export function init(track) {
}
}
- if (document.visibilityState === 'hidden' || document.visibilityState === 'prerender') {
- document.addEventListener('visibilitychange', handleVisibilityChange);
+ if (
+ document.visibilityState === 'hidden' ||
+ document.visibilityState === 'prerender'
+ ) {
+ document.addEventListener('visibilitychange', handleVisibilityChange)
} else {
page()
}
@@ -43,7 +48,7 @@ export function init(track) {
window.addEventListener('pageshow', function (event) {
if (event.persisted) {
// Page was restored from bfcache - track a pageview
- page();
+ page()
}
})
}
diff --git a/tracker/src/config.js b/tracker/src/config.js
index 9e516c2968..3577e72915 100644
--- a/tracker/src/config.js
+++ b/tracker/src/config.js
@@ -9,10 +9,10 @@ var config = {}
function defaultEndpoint() {
if (COMPILE_COMPAT) {
- var pathArray = scriptEl.src.split('/');
- var protocol = pathArray[0];
- var host = pathArray[2];
- return protocol + '//' + host + '/api/event';
+ 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'
}
@@ -23,14 +23,14 @@ export function getOptionsWithDefaults(initOptions) {
return Object.assign(initOptions, {
autoCapturePageviews: initOptions.autoCapturePageviews !== false,
logging: initOptions.logging !== false,
- lib: initOptions.lib || 'web',
+ lib: initOptions.lib || 'web'
})
}
if (COMPILE_PLAUSIBLE_NPM) {
return Object.assign(initOptions, {
autoCapturePageviews: initOptions.autoCapturePageviews !== false,
logging: initOptions.logging !== false,
- bindToWindow: initOptions.bindToWindow !== false,
+ bindToWindow: initOptions.bindToWindow !== false
})
}
}
@@ -38,10 +38,10 @@ export function getOptionsWithDefaults(initOptions) {
export function init(options) {
if (COMPILE_PLAUSIBLE_WEB) {
// This will be dynamically replaced by a config json object in the script serving endpoint
- config = "<%= @config_js %>"
+ config = '<%= @config_js %>'
Object.assign(config, options, {
// Explicitly set domain after other options are applied as `plausible-web` does not support overriding it, except by transformRequest
- domain: config.domain,
+ domain: config.domain
})
} else if (COMPILE_PLAUSIBLE_NPM) {
if (config.isInitialized) {
diff --git a/tracker/src/custom-events.js b/tracker/src/custom-events.js
index a9a67f9e28..e159dc23b9 100644
--- a/tracker/src/custom-events.js
+++ b/tracker/src/custom-events.js
@@ -3,14 +3,44 @@
import { config, scriptEl } from './config'
import { track } from './track'
-export var DEFAULT_FILE_TYPES = ['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']
+export var DEFAULT_FILE_TYPES = [
+ '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 MIDDLE_MOUSE_BUTTON = 1
var PARENTS_TO_SEARCH_LIMIT = 3
var fileTypesToTrack = DEFAULT_FILE_TYPES
function getLinkEl(link) {
- while (link && (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)) {
+ while (
+ link &&
+ (typeof link.tagName === 'undefined' || !isLink(link) || !link.href)
+ ) {
link = link.parentNode
}
return link
@@ -22,21 +52,34 @@ function isLink(element) {
function shouldInterceptNavigation(event, link) {
// If default has been prevented by an external script, Plausible should not intercept navigation.
- if (event.defaultPrevented) return false;
- var target = link.target;
+ if (event.defaultPrevented) return false
+ var target = link.target
// If the link directs to open the link in a different context, or we're not sure, do not intercept navigation
- if (target && (typeof target !== 'string' || !target.match(/^_(self|parent|top)$/i))) return false;
+ if (
+ target &&
+ (typeof target !== 'string' || !target.match(/^_(self|parent|top)$/i))
+ )
+ return false
// If the click is not a regular click (e.g. ctrl, meta, shift, or not a click event), do not intercept navigation
- if (event.ctrlKey || event.metaKey || event.shiftKey || event.type !== 'click') return false;
-
- return true;
+ if (
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey ||
+ event.type !== 'click'
+ )
+ return false
+
+ return true
}
function handleLinkClickEvent(event) {
- if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) {
+ return
+ }
var link = getLinkEl(event.target)
- var hrefWithoutQuery = link && typeof link.href === 'string' && link.href.split('?')[0]
+ var hrefWithoutQuery =
+ link && typeof link.href === 'string' && link.href.split('?')[0]
if (COMPILE_TAGGED_EVENTS) {
if (isElementOrParentTagged(link, 0)) {
@@ -48,13 +91,19 @@ function handleLinkClickEvent(event) {
if (COMPILE_OUTBOUND_LINKS && (!COMPILE_CONFIG || config.outboundLinks)) {
if (isOutboundLink(link)) {
- return sendLinkClickEvent(event, link, { name: 'Outbound Link: Click', props: { url: link.href } })
+ return sendLinkClickEvent(event, link, {
+ name: 'Outbound Link: Click',
+ props: { url: link.href }
+ })
}
}
if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {
if (isDownloadToTrack(hrefWithoutQuery)) {
- return sendLinkClickEvent(event, link, { name: 'File Download', props: { url: hrefWithoutQuery } })
+ return sendLinkClickEvent(event, link, {
+ name: 'File Download',
+ props: { url: hrefWithoutQuery }
+ })
}
}
}
@@ -64,22 +113,29 @@ function sendLinkClickEvent(event, link, eventAttrs) {
// or until analytics request finishes, otherwise navigation could prevent the analytics event from being sent.
var attrs
if (COMPILE_COMPAT) {
- var followedLink = false
- function followLink() {
- if (!followedLink) {
- followedLink = true
- window.location = link.href
+ var followedLink = false
+ function followLink() {
+ if (!followedLink) {
+ followedLink = true
+ window.location = link.href
+ }
}
- }
- if (shouldInterceptNavigation(event, link)) {
- attrs = { props: eventAttrs.props, callback: followLink }
- if (COMPILE_REVENUE) {
- attrs.revenue = eventAttrs.revenue
+ if (shouldInterceptNavigation(event, link)) {
+ attrs = { props: eventAttrs.props, callback: followLink }
+ if (COMPILE_REVENUE) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ track(eventAttrs.name, attrs)
+ setTimeout(followLink, 5000)
+ event.preventDefault()
+ } else {
+ attrs = { props: eventAttrs.props }
+ if (COMPILE_REVENUE) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ track(eventAttrs.name, attrs)
}
- track(eventAttrs.name, attrs)
- setTimeout(followLink, 5000)
- event.preventDefault()
} else {
attrs = { props: eventAttrs.props }
if (COMPILE_REVENUE) {
@@ -87,23 +143,23 @@ function sendLinkClickEvent(event, link, eventAttrs) {
}
track(eventAttrs.name, attrs)
}
- } else {
- attrs = { props: eventAttrs.props }
- if (COMPILE_REVENUE) {
- attrs.revenue = eventAttrs.revenue
- }
- track(eventAttrs.name, attrs)
- }
}
function isOutboundLink(link) {
- return link && typeof link.href === 'string' && link.host && link.host !== location.host
+ return (
+ link &&
+ typeof link.href === 'string' &&
+ link.host &&
+ link.host !== location.host
+ )
}
function isDownloadToTrack(url) {
- if (!url) { return false }
+ if (!url) {
+ return false
+ }
- var fileType = url.split('.').pop();
+ var fileType = url.split('.').pop()
return fileTypesToTrack.some(function (fileTypeToTrack) {
return fileTypeToTrack === fileType
})
@@ -113,29 +169,39 @@ 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 }
+ 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 }
+ if (!element || parentsChecked > PARENTS_TO_SEARCH_LIMIT) {
+ return false
+ }
+ if (isTagged(element)) {
+ return true
+ }
return isElementOrParentTagged(element.parentNode, parentsChecked + 1)
}
// 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 taggedElement = isTagged(htmlElement)
+ ? htmlElement
+ : htmlElement && htmlElement.parentNode
var eventAttrs = { name: null, props: {} }
if (COMPILE_REVENUE) {
eventAttrs.revenue = {}
}
var classList = taggedElement && taggedElement.classList
- if (!classList) { return eventAttrs }
+ if (!classList) {
+ return eventAttrs
+ }
for (var i = 0; i < classList.length; i++) {
var className = classList.item(i)
@@ -173,7 +239,10 @@ export function init() {
if (COMPILE_FILE_DOWNLOADS && (!COMPILE_CONFIG || config.fileDownloads)) {
if (COMPILE_CONFIG) {
- if (typeof config.fileDownloads === 'object' && Array.isArray(config.fileDownloads.fileExtensions)) {
+ if (
+ typeof config.fileDownloads === 'object' &&
+ Array.isArray(config.fileDownloads.fileExtensions)
+ ) {
fileTypesToTrack = config.fileDownloads.fileExtensions
}
} else {
@@ -181,13 +250,14 @@ export function init() {
var addFileTypesAttr = scriptEl.getAttribute('add-file-types')
if (fileTypesAttr) {
- fileTypesToTrack = fileTypesAttr.split(",")
+ fileTypesToTrack = fileTypesAttr.split(',')
}
if (addFileTypesAttr) {
- fileTypesToTrack = addFileTypesAttr.split(",").concat(DEFAULT_FILE_TYPES)
+ fileTypesToTrack = addFileTypesAttr
+ .split(',')
+ .concat(DEFAULT_FILE_TYPES)
}
}
-
}
if (COMPILE_CONFIG && config.formSubmissions) {
@@ -197,55 +267,61 @@ export function init() {
// If the form is tagged, we don't track it as a generic form submission.
return
}
- track('Form: Submission');
+ track('Form: Submission')
}
}
- document.addEventListener('submit', trackFormSubmission, true);
+ document.addEventListener('submit', trackFormSubmission, true)
}
if (COMPILE_TAGGED_EVENTS) {
function handleTaggedFormSubmitEvent(event) {
var form = event.target
var eventAttrs = getTaggedEventAttributes(form)
- if (!eventAttrs.name) { return }
-
+ if (!eventAttrs.name) {
+ return
+ }
+
var attrs
// In some legacy variants, this block delays submitting the form for up to 5 seconds,
// or until analytics request finishes, otherwise form-related navigation could prevent the analytics event from being sent.
if (COMPILE_COMPAT) {
- 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)
- attrs = { props: eventAttrs.props, callback: submitForm }
- if (COMPILE_REVENUE) {
- attrs.revenue = eventAttrs.revenue
- }
- track(eventAttrs.name, attrs)
+ attrs = { props: eventAttrs.props, callback: submitForm }
+ if (COMPILE_REVENUE) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ track(eventAttrs.name, attrs)
} else {
- attrs = { props: eventAttrs.props }
- if (COMPILE_REVENUE) {
- attrs.revenue = eventAttrs.revenue
- }
- track(eventAttrs.name, attrs)
+ attrs = { props: eventAttrs.props }
+ if (COMPILE_REVENUE) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ track(eventAttrs.name, attrs)
}
}
function isForm(element) {
- return element && element.tagName && element.tagName.toLowerCase() === 'form'
+ return (
+ element && element.tagName && element.tagName.toLowerCase() === 'form'
+ )
}
function handleTaggedElementClickEvent(event) {
- if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) { return }
+ if (event.type === 'auxclick' && event.button !== MIDDLE_MOUSE_BUTTON) {
+ return
+ }
var clicked = event.target
@@ -254,12 +330,20 @@ export function init() {
// 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 }
+ 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 }
+ if (isForm(clicked)) {
+ return
+ }
+ if (isLink(clicked)) {
+ clickedLink = clicked
+ }
+ if (isTagged(clicked)) {
+ taggedElement = clicked
+ }
clicked = clicked.parentNode
}
@@ -281,7 +365,6 @@ export function init() {
}
}
}
-
document.addEventListener('submit', handleTaggedFormSubmitEvent)
document.addEventListener('click', handleTaggedElementClickEvent)
diff --git a/tracker/src/engagement.js b/tracker/src/engagement.js
index ea30f6ca9b..fcc302169e 100644
--- a/tracker/src/engagement.js
+++ b/tracker/src/engagement.js
@@ -57,7 +57,11 @@ function triggerEngagement() {
Also, we don't send engagements if the current pageview is ignored (onIgnoredEvent)
*/
- if (!currentEngagementIgnored && (currentEngagementMaxScrollDepth < maxScrollDepthPx || engagementTime >= 3000)) {
+ if (
+ !currentEngagementIgnored &&
+ (currentEngagementMaxScrollDepth < maxScrollDepthPx ||
+ engagementTime >= 3000)
+ ) {
currentEngagementMaxScrollDepth = maxScrollDepthPx
var payload = {
@@ -83,7 +87,11 @@ function triggerEngagement() {
}
function onVisibilityChange() {
- if (document.visibilityState === 'visible' && document.hasFocus() && runningEngagementStart === 0) {
+ 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
@@ -112,7 +120,6 @@ function getEngagementTime() {
}
}
-
var currentDocumentHeight
var maxScrollDepthPx
@@ -135,7 +142,9 @@ function getCurrentScrollDepthPx() {
var viewportHeight = window.innerHeight || el.clientHeight || 0
var scrollTop = window.scrollY || el.scrollTop || body.scrollTop || 0
- return currentDocumentHeight <= viewportHeight ? currentDocumentHeight : scrollTop + viewportHeight
+ return currentDocumentHeight <= viewportHeight
+ ? currentDocumentHeight
+ : scrollTop + viewportHeight
}
export function init() {
@@ -151,7 +160,9 @@ export function init() {
var count = 0
var interval = setInterval(function () {
currentDocumentHeight = getDocumentHeight()
- if (++count === 15) { clearInterval(interval) }
+ if (++count === 15) {
+ clearInterval(interval)
+ }
}, 200)
})
diff --git a/tracker/src/networking.js b/tracker/src/networking.js
index 8bc4c0199f..51797b393b 100644
--- a/tracker/src/networking.js
+++ b/tracker/src/networking.js
@@ -1,17 +1,21 @@
export function sendRequest(endpoint, payload, options) {
if (COMPILE_COMPAT) {
- var request = new XMLHttpRequest();
- request.open('POST', endpoint, true);
- request.setRequestHeader('Content-Type', 'text/plain');
+ var request = new XMLHttpRequest()
+ request.open('POST', endpoint, true)
+ request.setRequestHeader('Content-Type', 'text/plain')
- request.send(JSON.stringify(payload));
+ request.send(JSON.stringify(payload))
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 0) {
- options && options.callback && options.callback({ error: new Error('Network error') })
+ options &&
+ options.callback &&
+ options.callback({ error: new Error('Network error') })
} else {
- options && options.callback && options.callback({ status: request.status })
+ options &&
+ options.callback &&
+ options.callback({ status: request.status })
}
}
}
@@ -24,11 +28,15 @@ export function sendRequest(endpoint, payload, options) {
},
keepalive: true,
body: JSON.stringify(payload)
- }).then(function (response) {
- options && options.callback && options.callback({ status: response.status })
- }).catch(function (error) {
- options && options.callback && options.callback({ error })
})
+ .then(function (response) {
+ options &&
+ options.callback &&
+ options.callback({ status: response.status })
+ })
+ .catch(function (error) {
+ options && options.callback && options.callback({ error })
+ })
}
}
}
diff --git a/tracker/src/track.js b/tracker/src/track.js
index 464d7c232b..1b2b0d4ed2 100644
--- a/tracker/src/track.js
+++ b/tracker/src/track.js
@@ -1,10 +1,16 @@
import { sendRequest } from './networking'
-import { prePageviewTrack, postPageviewTrack, onPageviewIgnored } from './engagement'
+import {
+ prePageviewTrack,
+ postPageviewTrack,
+ onPageviewIgnored
+} from './engagement'
import { config, scriptEl } from './config'
export function track(eventName, options) {
if (COMPILE_PLAUSIBLE_NPM && !config.isInitialized) {
- throw new Error('plausible.track() can only be called after plausible.init()')
+ throw new Error(
+ 'plausible.track() can only be called after plausible.init()'
+ )
}
var isPageview = eventName === 'pageview'
@@ -14,10 +20,21 @@ export function track(eventName, options) {
}
if (!(COMPILE_LOCAL && (!COMPILE_CONFIG || config.captureOnLocalhost))) {
- if (/^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/.test(location.hostname) || location.protocol === 'file:') {
+ if (
+ /^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/.test(
+ location.hostname
+ ) ||
+ location.protocol === 'file:'
+ ) {
return onIgnoredEvent(eventName, options, 'localhost')
}
- if ((window._phantom || window.__nightmare || window.navigator.webdriver || window.Cypress) && !window.__plausible) {
+ if (
+ (window._phantom ||
+ window.__nightmare ||
+ window.navigator.webdriver ||
+ window.Cypress) &&
+ !window.__plausible
+ ) {
return onIgnoredEvent(eventName, options)
}
}
@@ -40,15 +57,29 @@ export function track(eventName, options) {
actualPath += location.hash
}
- // eslint-disable-next-line no-useless-escape
- return actualPath.match(new RegExp('^' + wildcardPath.trim().replace(/\*\*/g, '.*').replace(/([^\.])\*/g, '$1[^\\s\/]*') + '\/?$'))
+ return actualPath.match(
+ new RegExp(
+ '^' +
+ wildcardPath
+ .trim()
+ .replace(/\*\*/g, '.*')
+ // eslint-disable-next-line no-useless-escape
+ .replace(/([^\.])\*/g, '$1[^\\s\/]*') +
+ // eslint-disable-next-line no-useless-escape
+ '\/?$'
+ )
+ )
}
if (isPageview) {
- var isIncluded = !dataIncludeAttr || (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))
- var isExcluded = dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)
-
- if (!isIncluded || isExcluded) return onIgnoredEvent(eventName, options, 'exclusion rule')
+ var isIncluded =
+ !dataIncludeAttr ||
+ (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))
+ var isExcluded =
+ dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)
+
+ if (!isIncluded || isExcluded)
+ return onIgnoredEvent(eventName, options, 'exclusion rule')
}
}
@@ -114,7 +145,10 @@ export function track(eventName, options) {
payload.h = 1
}
- if ((COMPILE_PLAUSIBLE_WEB || COMPILE_PLAUSIBLE_NPM) && typeof config.transformRequest === 'function') {
+ if (
+ (COMPILE_PLAUSIBLE_WEB || COMPILE_PLAUSIBLE_NPM) &&
+ typeof config.transformRequest === 'function'
+ ) {
payload = config.transformRequest(payload)
if (!payload) {
@@ -129,10 +163,9 @@ export function track(eventName, options) {
sendRequest(config.endpoint, payload, options)
}
-
function onIgnoredEvent(eventName, options, reason) {
if (reason && config.logging) {
- console.warn('Ignoring Event: ' + reason);
+ console.warn('Ignoring Event: ' + reason)
}
options && options.callback && options.callback()
diff --git a/tracker/src/web-snippet.js b/tracker/src/web-snippet.js
index 28a804c3f1..1eb5701180 100644
--- a/tracker/src/web-snippet.js
+++ b/tracker/src/web-snippet.js
@@ -1,12 +1,16 @@
// This snippet is shown to users to install plausible tracker script
//<script>
-window.plausible = window.plausible || function() {
- (plausible.q = plausible.q || []).push(arguments)
-}
-plausible.init = plausible.init || function(overrides) {
- plausible.o = overrides || {}
-}
+window.plausible =
+ window.plausible ||
+ function () {
+ ;(plausible.q = plausible.q || []).push(arguments)
+ }
+plausible.init =
+ plausible.init ||
+ function (overrides) {
+ plausible.o = overrides || {}
+ }
// plausible.init()
//</script>
diff --git a/tracker/test/callbacks.spec.ts b/tracker/test/callbacks.spec.ts
index ffdaafdfc6..383e078654 100644
--- a/tracker/test/callbacks.spec.ts
+++ b/tracker/test/callbacks.spec.ts
@@ -37,7 +37,7 @@ for (const mode of ['web', 'esm', 'legacy']) {
apiPath: 'h://no-exist',
mockPath: `/api/event`,
fulfill: { status: 202 },
- expectedResult: { error: expect.any(Error)}
+ expectedResult: { error: expect.any(Error) }
},
{
name: 'on ignored request (because of not having capturing events on localhost)',
diff --git a/tracker/test/custom-properties.spec.ts b/tracker/test/custom-properties.spec.ts
index 60971e64fd..1b49a0bbb0 100644
--- a/tracker/test/custom-properties.spec.ts
+++ b/tracker/test/custom-properties.spec.ts
@@ -163,7 +163,11 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<button onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })">Subscribe</button>`
+ bodyContent: /* HTML */ `<button
+ onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })"
+ >
+ Subscribe
+ </button>`
})
await expectPlausibleInAction(page, {
@@ -210,7 +214,11 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<button onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })">Subscribe</button>`
+ bodyContent: /* HTML */ `<button
+ onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })"
+ >
+ Subscribe
+ </button>`
})
await expectPlausibleInAction(page, {
@@ -253,7 +261,11 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<button onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })">Subscribe</button>`
+ bodyContent: /* HTML */ `<button
+ onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })"
+ >
+ Subscribe
+ </button>`
})
await expectPlausibleInAction(page, {
diff --git a/tracker/test/engagement.spec.js b/tracker/test/engagement.spec.js
index 46cc4d949e..af325f7ac4 100644
--- a/tracker/test/engagement.spec.js
+++ b/tracker/test/engagement.spec.js
@@ -1,30 +1,47 @@
-import { expect } from "@playwright/test"
-import { expectPlausibleInAction, hideAndShowCurrentTab, focus, blur, blurAndFocusPage, tracker_script_version } from './support/test-utils'
+import { expect } from '@playwright/test'
+import {
+ expectPlausibleInAction,
+ hideAndShowCurrentTab,
+ focus,
+ blur,
+ blurAndFocusPage,
+ tracker_script_version
+} from './support/test-utils'
import { test } from '@playwright/test'
import { LOCAL_SERVER_ADDR } from './support/server'
test.describe('engagement events', () => {
- test('sends an engagement event with time measurement when navigating to the next page', async ({ page }) => {
+ test('sends an engagement event with time measurement when navigating to the next page', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.waitForTimeout(1000)
const [request] = await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`, v: tracker_script_version}]
+ expectedRequests: [
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/engagement.html`,
+ v: tracker_script_version
+ }
+ ]
})
expect(request.e).toBeGreaterThan(1000)
expect(request.e).toBeLessThan(1500)
})
- test('sends an event and a pageview on hash-based SPA navigation', async ({ page }) => {
+ test('sends an event and a pageview on hash-based SPA navigation', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement-hash.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.waitForTimeout(1000)
@@ -32,8 +49,11 @@ test.describe('engagement events', () => {
const [request] = await expectPlausibleInAction(page, {
action: () => page.click('#hash-nav'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`}
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html` },
+ {
+ n: 'pageview',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`
+ }
]
})
@@ -41,10 +61,12 @@ test.describe('engagement events', () => {
expect(request.e).toBeLessThan(1500)
})
- test('sends an event and a pageview on history-based SPA navigation', async ({ page }) => {
+ test('sends an event and a pageview on history-based SPA navigation', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.waitForTimeout(1000)
@@ -52,8 +74,8 @@ test.describe('engagement events', () => {
const [request] = await expectPlausibleInAction(page, {
action: () => page.click('#history-nav'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/another-page`}
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` },
+ { n: 'pageview', u: `${LOCAL_SERVER_ADDR}/another-page` }
]
})
@@ -61,10 +83,12 @@ test.describe('engagement events', () => {
expect(request.e).toBeLessThan(1500)
})
- test('sends engagements when pageviews are triggered manually on a SPA', async ({ page }) => {
+ test('sends engagements when pageviews are triggered manually on a SPA', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement-hash-manual.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.waitForTimeout(1000)
@@ -72,8 +96,8 @@ test.describe('engagement events', () => {
const [request] = await expectPlausibleInAction(page, {
action: () => page.click('#about-us-hash-link'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/#home`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/#about-us`}
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/#home` },
+ { n: 'pageview', u: `${LOCAL_SERVER_ADDR}/#about-us` }
]
})
@@ -86,45 +110,53 @@ test.describe('engagement events', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#pageview-trigger-custom-url'),
- expectedRequests: [{n: 'pageview', u: 'https://example.com/custom/location'}],
+ expectedRequests: [
+ { n: 'pageview', u: 'https://example.com/custom/location' }
+ ]
})
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', u: 'https://example.com/custom/location'}]
+ expectedRequests: [
+ { n: 'engagement', u: 'https://example.com/custom/location' }
+ ]
})
})
- test('does not send an event when pageview was not sent in manual mode', async ({ page }) => {
+ test('does not send an event when pageview was not sent in manual mode', async ({
+ page
+ }) => {
await page.goto('/engagement-manual.html')
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- refutedRequests: [{n: 'engagement'}]
+ refutedRequests: [{ n: 'engagement' }]
})
})
- test('script.exclusions.hash.js sends an event only from URLs where a pageview was sent', async ({ page }) => {
+ test('script.exclusions.hash.js sends an event only from URLs where a pageview was sent', async ({
+ page
+ }) => {
const pageBaseURL = `${LOCAL_SERVER_ADDR}/engagement-hash-exclusions.html`
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement-hash-exclusions.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
// After the initial pageview is sent, navigate to ignored page ->
// engagement event is sent from the initial page URL
await expectPlausibleInAction(page, {
action: () => page.click('#ignored-hash-link'),
- expectedRequests: [{n: 'engagement', u: pageBaseURL, h: 1}]
+ expectedRequests: [{ n: 'engagement', u: pageBaseURL, h: 1 }]
})
// Navigate from ignored page to a tracked page ->
// no engagement from the current page, pageview on the next page
await expectPlausibleInAction(page, {
action: () => page.click('#hash-link-1'),
- expectedRequests: [{n: 'pageview', u: `${pageBaseURL}#hash1`, h: 1}],
- refutedRequests: [{n: 'engagement'}]
+ expectedRequests: [{ n: 'pageview', u: `${pageBaseURL}#hash1`, h: 1 }],
+ refutedRequests: [{ n: 'engagement' }]
})
// Navigate from a tracked page to another tracked page ->
@@ -132,94 +164,109 @@ test.describe('engagement events', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#hash-link-2'),
expectedRequests: [
- {n: 'engagement', u: `${pageBaseURL}#hash1`, h: 1},
- {n: 'pageview', u: `${pageBaseURL}#hash2`, h: 1}
+ { n: 'engagement', u: `${pageBaseURL}#hash1`, h: 1 },
+ { n: 'pageview', u: `${pageBaseURL}#hash2`, h: 1 }
]
})
})
- test('sends an event with the same props as pageview (manual extension)', async ({ page }) => {
+ test('sends an event with the same props as pageview (manual extension)', async ({
+ page
+ }) => {
await page.goto('/engagement-manual.html')
await expectPlausibleInAction(page, {
action: () => page.click('#pageview-trigger-custom-props'),
- expectedRequests: [{n: 'pageview', p: {author: 'John'}}],
+ expectedRequests: [{ n: 'pageview', p: { author: 'John' } }]
})
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', p: {author: 'John'}}]
+ expectedRequests: [{ n: 'engagement', p: { author: 'John' } }]
})
})
- test('sends an event with the same props as pageview (pageview-props extension)', async ({ page }) => {
+ 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', index: "0"}}],
+ expectedRequests: [{ n: 'pageview', p: { author: 'John', index: '0' } }]
})
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', p: {author: 'John', index: "0"}}]
+ expectedRequests: [{ n: 'engagement', p: { author: 'John', index: '0' } }]
})
})
- test('pageview props with custom events and values changing mid-view (pageview-props extension)', async ({ page }) => {
+ 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"}}],
+ 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"}}]
+ 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"}}]
+ expectedRequests: [{ n: 'engagement', p: { author: 'John', index: '0' } }]
})
})
- test('sends an event with the same props as pageview (hash navigation / pageview-props extension)', async ({ page }) => {
+ test('sends an event with the same props as pageview (hash navigation / pageview-props extension)', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement-hash-pageview-props.html'),
- expectedRequests: [{n: 'pageview', p: {}}],
+ expectedRequests: [{ n: 'pageview', p: {} }]
})
await expectPlausibleInAction(page, {
action: () => page.click('#john-post'),
expectedRequests: [
- {n: 'engagement', p: {}},
- {n: 'pageview', p: {author: 'john'}}
+ { n: 'engagement', p: {} },
+ { n: 'pageview', p: { author: 'john' } }
]
})
await expectPlausibleInAction(page, {
action: () => page.click('#jane-post'),
expectedRequests: [
- {n: 'engagement', p: {author: 'john'}},
- {n: 'pageview', p: {author: 'jane'}}
+ { n: 'engagement', p: { author: 'john' } },
+ { n: 'pageview', p: { author: 'jane' } }
]
})
await expectPlausibleInAction(page, {
action: () => page.click('#home'),
expectedRequests: [
- {n: 'engagement', p: {author: 'jane'}},
- {n: 'pageview', p: {}}
+ { n: 'engagement', p: { author: 'jane' } },
+ { n: 'pageview', p: {} }
]
})
})
- test('sends an event when plausible API is slow and user navigates away before response is received', async ({ page, browserName }) => {
+ test('sends an event when plausible API is slow and user navigates away before response is received', async ({
+ page,
+ browserName
+ }) => {
test.skip(browserName === 'chromium', 'flaky')
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement.html'),
- expectedRequests: [{n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ expectedRequests: [
+ { n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
await expectPlausibleInAction(page, {
@@ -229,47 +276,65 @@ test.describe('engagement events', () => {
await page.click('#back-button-trigger')
},
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`},
- {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`}
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` },
+ {
+ 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
})
})
- test('sends engagement events when tab toggles between foreground and background', async ({ page }) => {
+ test('sends engagement events when tab toggles between foreground and background', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
const [request1] = await expectPlausibleInAction(page, {
- action: () => hideAndShowCurrentTab(page, {delay: 2000}),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ action: () => hideAndShowCurrentTab(page, { delay: 2000 }),
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
expect(request1.e).toBeLessThan(500)
await page.waitForTimeout(3000)
const [request2] = await expectPlausibleInAction(page, {
- action: () => hideAndShowCurrentTab(page, {delay: 2000}),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ action: () => hideAndShowCurrentTab(page, { delay: 2000 }),
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
expect(request2.e).toBeGreaterThan(3000)
expect(request2.e).toBeLessThan(3500)
})
- test('does not send engagement events when tab is only open for a short time until over 3000ms has passed', async ({ page }) => {
+ test('does not send engagement events when tab is only open for a short time until over 3000ms has passed', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
const [request1] = await expectPlausibleInAction(page, {
action: () => hideAndShowCurrentTab(page),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
expect(request1.e).toBeLessThan(500)
@@ -277,15 +342,17 @@ test.describe('engagement events', () => {
await expectPlausibleInAction(page, {
action: () => hideAndShowCurrentTab(page),
- refutedRequests: [{n: 'engagement'}],
+ refutedRequests: [{ n: 'engagement' }],
mockRequestTimeout: 100
})
await page.waitForTimeout(2500)
const [request2] = await expectPlausibleInAction(page, {
- action: () => hideAndShowCurrentTab(page, {delay: 3000}),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ action: () => hideAndShowCurrentTab(page, { delay: 3000 }),
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
// Sum of both visibility times
@@ -296,7 +363,7 @@ test.describe('engagement events', () => {
test('tracks engagement time properly in a SPA', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement-hash.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.waitForTimeout(1000)
@@ -304,8 +371,11 @@ test.describe('engagement events', () => {
const [request] = await expectPlausibleInAction(page, {
action: () => page.click('#hash-nav'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`}
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html` },
+ {
+ n: 'pageview',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`
+ }
]
})
@@ -315,8 +385,14 @@ test.describe('engagement events', () => {
const [request2] = await expectPlausibleInAction(page, {
action: () => page.click('#hash-nav-2'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#another-hash`}
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`
+ },
+ {
+ n: 'pageview',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#another-hash`
+ }
]
})
@@ -326,7 +402,12 @@ test.describe('engagement events', () => {
const [request3] = await expectPlausibleInAction(page, {
action: () => hideAndShowCurrentTab(page),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#another-hash`}],
+ expectedRequests: [
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#another-hash`
+ }
+ ]
})
expect(request3.e).toBeGreaterThan(3000)
@@ -336,8 +417,14 @@ test.describe('engagement events', () => {
const [request4] = await expectPlausibleInAction(page, {
action: () => page.click('#hash-nav'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#another-hash`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`}
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#another-hash`
+ },
+ {
+ n: 'pageview',
+ u: `${LOCAL_SERVER_ADDR}/engagement-hash.html#some-hash`
+ }
]
})
@@ -345,15 +432,19 @@ test.describe('engagement events', () => {
expect(request4.e).toBeLessThan(3500)
})
- test('tracks engagement time whilst tab gains and loses focus', async ({ page }) => {
+ test('tracks engagement time whilst tab gains and loses focus', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/engagement.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
const [request1] = await expectPlausibleInAction(page, {
action: () => blur(page),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
expect(request1.e).toBeLessThan(500)
@@ -362,7 +453,7 @@ test.describe('engagement events', () => {
await expectPlausibleInAction(page, {
action: () => blurAndFocusPage(page, { delay: 3000 }),
- refutedRequests: [{n: 'engagement'}],
+ refutedRequests: [{ n: 'engagement' }],
mockRequestTimeout: 100
})
@@ -370,7 +461,9 @@ test.describe('engagement events', () => {
const [request2] = await expectPlausibleInAction(page, {
action: () => blur(page),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html`}],
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/engagement.html` }
+ ]
})
expect(request2.e).toBeGreaterThan(3500)
diff --git a/tracker/test/features-hierarchy-on-overlap.spec.ts b/tracker/test/features-hierarchy-on-overlap.spec.ts
index 58f56becf4..63ea5b1c8a 100644
--- a/tracker/test/features-hierarchy-on-overlap.spec.ts
+++ b/tracker/test/features-hierarchy-on-overlap.spec.ts
@@ -50,7 +50,11 @@ for (const mode of ['legacy', 'web'] as const) {
},
mode
),
- bodyContent: `<a class="plausible-event-name=Custom+Event" href="${downloadUrl}">Outbound Download</a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-name=Custom+Event"
+ href="${downloadUrl}"
+ >Outbound Download</a
+ >`
})
await page.goto(url)
@@ -93,7 +97,7 @@ for (const mode of ['legacy', 'web'] as const) {
},
mode
),
- bodyContent: `<a href="${downloadUrl}">Get file</a>`
+ bodyContent: /* HTML */ `<a href="${downloadUrl}">Get file</a>`
})
await page.goto(url)
@@ -137,7 +141,7 @@ for (const mode of ['legacy', 'web'] as const) {
},
mode
),
- bodyContent: `<a href="${downloadUrl}">Get file</a>`
+ bodyContent: /* HTML */ `<a href="${downloadUrl}">Get file</a>`
})
await page.goto(url)
@@ -159,9 +163,9 @@ for (const mode of ['legacy', 'web'] as const) {
for (const mode of ['web', 'esm'] as const) {
test.describe(`form submissions and tagged events features hierarchy on overlap v2-specific (${mode})`, () => {
- test('sends only tagged event if a form is tagged', async ({
- page
- }, { testId }) => {
+ test('sends only tagged event if a form is tagged', async ({ page }, {
+ testId
+ }) => {
const config = { ...DEFAULT_CONFIG, formSubmissions: true }
const { url } = await initializePageDynamically(page, {
testId,
@@ -178,9 +182,12 @@ for (const mode of ['web', 'esm'] as const) {
},
mode
),
- bodyContent: `
+ bodyContent: /* HTML */ `
<form method="POST" class="plausible-event-name=A+Tagged+Form">
- <input id="name" type="text" placeholder="Name" /><input type="submit" value="Submit" />
+ <input id="name" type="text" placeholder="Name" /><input
+ type="submit"
+ value="Submit"
+ />
</form>
`
})
@@ -223,7 +230,7 @@ for (const mode of ['web', 'esm'] as const) {
},
mode
),
- bodyContent: `
+ bodyContent: /* HTML */ `
<div class="plausible-event-name--A+Tagged+Form">
<form onsubmit="${customSubmitHandlerStub}">
<input type="email" />
diff --git a/tracker/test/file-downloads.spec.ts b/tracker/test/file-downloads.spec.ts
index dd6192e863..757f76757f 100644
--- a/tracker/test/file-downloads.spec.ts
+++ b/tracker/test/file-downloads.spec.ts
@@ -45,7 +45,7 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<a href="${filePath}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${filePath}">📥</a>`
})
await expectPlausibleInAction(page, {
@@ -90,7 +90,7 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<a href="${filePath}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${filePath}">📥</a>`
})
await expectPlausibleInAction(page, {
@@ -149,7 +149,8 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<a href="${isoFileURL}" target="_blank">📥</a><a href="${csvFileURL}" target="_blank">📥</a>`
+ bodyContent: /* HTML */ `<a href="${isoFileURL}" target="_blank">📥</a
+ ><a href="${csvFileURL}" target="_blank">📥</a>`
})
await page.goto(url)
await expectPlausibleInAction(page, {
@@ -193,7 +194,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${filePath}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${filePath}">📥</a>`
})
await page.goto(url)
@@ -230,7 +231,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${pdfUrl}" target="_blank">📥</a>`
+ bodyContent: /* HTML */ `<a href="${pdfUrl}" target="_blank">📥</a>`
})
await page.goto(url)
@@ -270,7 +271,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${pdfUrl}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${pdfUrl}">📥</a>`
})
await page.goto(url)
@@ -305,7 +306,9 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${pdfUrl}"><div><span>📥</span></div></a>`
+ bodyContent: /* HTML */ `<a href="${pdfUrl}"
+ ><div><span>📥</span></div></a
+ >`
})
await page.goto(url)
@@ -350,7 +353,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${pdfUrl}">Download</a>`
+ bodyContent: /* HTML */ `<a href="${pdfUrl}">Download</a>`
})
await page.goto(url)
await page.click('a')
@@ -396,7 +399,9 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${pdfUrl}?user=foo%secret=123">Download PDF</a>`
+ bodyContent: /* HTML */ `<a href="${pdfUrl}?user=foo%secret=123"
+ >Download PDF</a
+ >`
})
await page.goto(url)
@@ -430,7 +435,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="https://example.com/file.iso">📥</a>`
+ bodyContent: /* HTML */ `<a href="https://example.com/file.iso">📥</a>`
})
await page.goto(url)
@@ -476,7 +481,8 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a href="${isoFileURL}" target="_blank">📥</a><a href="${csvFileURL}" target="_blank">📥</a>`
+ bodyContent: /* HTML */ `<a href="${isoFileURL}" target="_blank">📥</a
+ ><a href="${csvFileURL}" target="_blank">📥</a>`
})
await page.goto(url)
await expectPlausibleInAction(page, {
@@ -517,9 +523,11 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `
- <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><a href="${csvFileURL}"><circle cx="50" cy="50" r="50" /></a></svg>
- `
+ bodyContent: /* HTML */ `
+ <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
+ <a href="${csvFileURL}"><circle cx="50" cy="50" r="50" /></a>
+ </svg>
+ `
})
const pageErrors: Error[] = []
@@ -603,7 +611,9 @@ test.describe('file downloads feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.file-downloads.local.manual.js"></script>',
- bodyContent: `<a ${linkAttributes} href="${filePath}"><h1>📥</h1></a>`
+ bodyContent: /* HTML */ `<a ${linkAttributes} href="${filePath}"
+ ><h1>📥</h1></a
+ >`
})
await page.goto(url)
await page.click(click.element, { modifiers: click.modifiers })
@@ -668,7 +678,7 @@ test.describe('file downloads feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.file-downloads.local.manual.js"></script>',
- bodyContent: `<a href="${filePath}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${filePath}">📥</a>`
})
await page.goto(url)
@@ -721,7 +731,7 @@ test.describe('file downloads feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.file-downloads.local.manual.js"></script>',
- bodyContent: `<a href="${filePath}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${filePath}">📥</a>`
})
await page.goto(url)
const navigationPromise = page.waitForRequest(filePath, {
diff --git a/tracker/test/fixtures/cookies-cookiebot.html b/tracker/test/fixtures/cookies-cookiebot.html
index e1047d7b09..92c9080d8c 100644
--- a/tracker/test/fixtures/cookies-cookiebot.html
+++ b/tracker/test/fixtures/cookies-cookiebot.html
@@ -1,11 +1,11 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Plausible Playwright tests</title>
</head>
- <!-- This was copied from the dogfood cookie banner that appears at https://www.cookiebot.com -->
+ <!-- This was copied from the dogfood cookie banner that appears at https://www.cookiebot.com -->
<body>
cookiebot fixture
<div
@@ -4686,8 +4686,8 @@
style="
box-sizing: inherit;
color: rgba(209, 210, 211, 1);
- font-family: Slack-Lato, Slack-Fractions, appleLogo,
- sans-serif;
+ font-family:
+ Slack-Lato, Slack-Fractions, appleLogo, sans-serif;
font-size: 15px;
font-variant-ligatures: common-ligatures;
background-color: rgba(34, 37, 41, 1);
diff --git a/tracker/test/fixtures/cookies-iubenda.html b/tracker/test/fixtures/cookies-iubenda.html
index e35bb96e3e..36f279fcc4 100644
--- a/tracker/test/fixtures/cookies-iubenda.html
+++ b/tracker/test/fixtures/cookies-iubenda.html
@@ -1,10 +1,10 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Plausible Playwright tests</title>
</head>
-
+
<!-- This was copied from the dogfood cookie banner that appears at https://www.iubenda.com -->
<body>
iubenda fixture
diff --git a/tracker/test/fixtures/cookies-onetrust.html b/tracker/test/fixtures/cookies-onetrust.html
index dabc16b846..4ed7275e3e 100644
--- a/tracker/test/fixtures/cookies-onetrust.html
+++ b/tracker/test/fixtures/cookies-onetrust.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
diff --git a/tracker/test/fixtures/cookies-quantcast.html b/tracker/test/fixtures/cookies-quantcast.html
index 31825cdf08..77de8238c1 100644
--- a/tracker/test/fixtures/cookies-quantcast.html
+++ b/tracker/test/fixtures/cookies-quantcast.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
diff --git a/tracker/test/fixtures/engagement-hash-exclusions.html b/tracker/test/fixtures/engagement-hash-exclusions.html
index 5133f5ef45..38c1568006 100644
--- a/tracker/test/fixtures/engagement-hash-exclusions.html
+++ b/tracker/test/fixtures/engagement-hash-exclusions.html
@@ -1,18 +1,22 @@
-<!DOCTYPE html>
+<!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
+ async
+ data-exclude="/*#*/hash/**/ignored"
+ src="/tracker/js/plausible.exclusions.hash.local.js"
+ ></script>
+ </head>
-<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 async data-exclude='/*#*/hash/**/ignored' src="/tracker/js/plausible.exclusions.hash.local.js"></script>
-</head>
-
-<body>
- <a id="ignored-hash-link" href="#this/hash/should/be/ignored">Ignored Hash Link</a>
- <a id="hash-link-1" href="#hash1">Hash Link 1</a>
- <a id="hash-link-2" href="#hash2">Hash Link 2</a>
-</body>
-
+ <body>
+ <a id="ignored-hash-link" href="#this/hash/should/be/ignored"
+ >Ignored Hash Link</a
+ >
+ <a id="hash-link-1" href="#hash1">Hash Link 1</a>
+ <a id="hash-link-2" href="#hash2">Hash Link 2</a>
+ </body>
</html>
diff --git a/tracker/test/fixtures/engagement-hash-manual.html b/tracker/test/fixtures/engagement-hash-manual.html
index 4195a12964..a0d0aa6a78 100644
--- a/tracker/test/fixtures/engagement-hash-manual.html
+++ b/tracker/test/fixtures/engagement-hash-manual.html
@@ -1,39 +1,43 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.hash.local.manual.js"></script>
+ <script>
+ window.plausible =
+ window.plausible ||
+ function () {
+ ;(window.plausible.q = window.plausible.q || []).push(arguments)
+ }
+ </script>
+ </head>
-<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 async src="/tracker/js/plausible.hash.local.manual.js"></script>
- <script>window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }</script>
-</head>
+ <body>
+ <a id="about-us-hash-link" href="#about">About us</a>
+ <a id="home-hash-link" href="#home">Home</a>
-<body>
- <a id="about-us-hash-link" href="#about">About us</a>
- <a id="home-hash-link" href="#home">Home</a>
+ <div>
+ <p id="page-title">Home</p>
+ </div>
- <div>
- <p id="page-title">Home</p>
- </div>
+ <script>
+ const titleNode = document.getElementById('page-title')
- <script>
- const titleNode = document.getElementById('page-title')
-
- function updateContent() {
- if (location.hash === '#about') {
- titleNode.innerHTML = 'About us'
- window.plausible('pageview', {u: 'http://localhost:3000/#about-us'})
- } else {
- titleNode.innerHTML = 'Home'
- window.plausible('pageview', {u: 'http://localhost:3000/#home'})
+ function updateContent() {
+ if (location.hash === '#about') {
+ titleNode.innerHTML = 'About us'
+ window.plausible('pageview', { u: 'http://localhost:3000/#about-us' })
+ } else {
+ titleNode.innerHTML = 'Home'
+ window.plausible('pageview', { u: 'http://localhost:3000/#home' })
+ }
}
- }
-
- window.plausible('pageview', {u: 'http://localhost:3000/#home'})
- window.addEventListener('hashchange', updateContent);
- </script>
-</body>
+ window.plausible('pageview', { u: 'http://localhost:3000/#home' })
+ window.addEventListener('hashchange', updateContent)
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/engagement-hash-pageview-props.html b/tracker/test/fixtures/engagement-hash-pageview-props.html
index 0953b8de31..b21777098e 100644
--- a/tracker/test/fixtures/engagement-hash-pageview-props.html
+++ b/tracker/test/fixtures/engagement-hash-pageview-props.html
@@ -1,36 +1,47 @@
-<!DOCTYPE html>
+<!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
+ id="plausible-script"
+ async
+ src="/tracker/js/plausible.hash.local.pageview-props.js"
+ ></script>
+ </head>
-<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 id="plausible-script" async src="/tracker/js/plausible.hash.local.pageview-props.js"></script>
-</head>
+ <body>
+ <h1>Blog</h1>
-<body>
- <h1>Blog</h1>
+ <button id="home" onclick="goHome()">Home</button>
+ <button id="john-post" onclick="goToBlogPost('john')">
+ A blog post of John
+ </button>
+ <button id="jane-post" onclick="goToBlogPost('jane')">
+ A blog post of Jane
+ </button>
- <button id="home" onclick="goHome()">Home</button>
- <button id="john-post" onclick="goToBlogPost('john')">A blog post of John</button>
- <button id="jane-post" onclick="goToBlogPost('jane')">A blog post of Jane</button>
+ <div id="content"></div>
- <div id="content"></div>
-
- <script>
- function goToBlogPost(author) {
- document.getElementById('plausible-script').setAttribute('event-author', author)
- window.location.hash = `/${author}-post`
- document.getElementById('content').innerHTML = `Hello, I'm ${author} and this is my post.`
- }
-
- function goHome() {
- document.getElementById('plausible-script').removeAttribute('event-author')
- window.location.hash = ''
- document.getElementById('content').innerHTML = ''
- }
- </script>
-</body>
+ <script>
+ function goToBlogPost(author) {
+ document
+ .getElementById('plausible-script')
+ .setAttribute('event-author', author)
+ window.location.hash = `/${author}-post`
+ document.getElementById('content').innerHTML =
+ `Hello, I'm ${author} and this is my post.`
+ }
+ function goHome() {
+ document
+ .getElementById('plausible-script')
+ .removeAttribute('event-author')
+ window.location.hash = ''
+ document.getElementById('content').innerHTML = ''
+ }
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/engagement-hash.html b/tracker/test/fixtures/engagement-hash.html
index a70812b38a..b6a3cf049e 100644
--- a/tracker/test/fixtures/engagement-hash.html
+++ b/tracker/test/fixtures/engagement-hash.html
@@ -1,20 +1,16 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.hash.local.js"></script>
+ <script></script>
+ </head>
-<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 async src="/tracker/js/plausible.hash.local.js"></script>
- <script>
-
- </script>
-</head>
-
-<body>
- <a id="hash-nav" href="#some-hash">Hash link</a>
- <a id="hash-nav-2" href="#another-hash">Another hash link</a>
-</body>
-
+ <body>
+ <a id="hash-nav" href="#some-hash">Hash link</a>
+ <a id="hash-nav-2" href="#another-hash">Another hash link</a>
+ </body>
</html>
diff --git a/tracker/test/fixtures/engagement-manual.html b/tracker/test/fixtures/engagement-manual.html
index ca135d38a1..3d64b8ffcc 100644
--- a/tracker/test/fixtures/engagement-manual.html
+++ b/tracker/test/fixtures/engagement-manual.html
@@ -1,34 +1,40 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.local.manual.js"></script>
+ <script>
+ window.plausible =
+ window.plausible ||
+ function () {
+ ;(window.plausible.q = window.plausible.q || []).push(arguments)
+ }
+ </script>
+ </head>
-<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 async src="/tracker/js/plausible.local.manual.js"></script>
- <script>window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }</script>
-</head>
+ <body>
+ <a id="navigate-away" href="/manual.html">Navigate away</a>
-<body>
- <a id="navigate-away" href="/manual.html">Navigate away</a>
-
- <button id="pageview-trigger-custom-url">
- Triggers a pageview with custom URL
- </button>
- <button id="pageview-trigger-custom-props">
- Triggers a pageview with custom props
- </button>
-
- <script>
- document.addEventListener('click', (e) => {
- if (e.target.id === 'pageview-trigger-custom-url') {
- window.plausible('pageview', {u: 'https://example.com/custom/location'})
- } else if (e.target.id === 'pageview-trigger-custom-props') {
- window.plausible('pageview', {props: {author: 'John'}})
- }
- })
- </script>
-</body>
+ <button id="pageview-trigger-custom-url">
+ Triggers a pageview with custom URL
+ </button>
+ <button id="pageview-trigger-custom-props">
+ Triggers a pageview with custom props
+ </button>
+ <script>
+ document.addEventListener('click', (e) => {
+ if (e.target.id === 'pageview-trigger-custom-url') {
+ window.plausible('pageview', {
+ u: 'https://example.com/custom/location'
+ })
+ } else if (e.target.id === 'pageview-trigger-custom-props') {
+ window.plausible('pageview', { props: { author: 'John' } })
+ }
+ })
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/engagement-pageview-props.html b/tracker/test/fixtures/engagement-pageview-props.html
index 90803a46f7..cdea2320ec 100644
--- a/tracker/test/fixtures/engagement-pageview-props.html
+++ b/tracker/test/fixtures/engagement-pageview-props.html
@@ -1,28 +1,42 @@
-<!DOCTYPE html>
+<!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
+ async
+ event-author="John"
+ src="/tracker/js/plausible.local.pageview-props.js"
+ ></script>
+ </head>
-<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 async event-author="John" src="/tracker/js/plausible.local.pageview-props.js"></script>
-</head>
+ <body>
+ <a id="navigate-away" href="/manual.html">Navigate away</a>
+ <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>
-<body>
- <a id="navigate-away" href="/manual.html">Navigate away</a>
- <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>
+ var i = 0
-<script>
- var i = 0
+ function increment() {
+ document
+ .getElementsByTagName('script')[0]
+ .setAttribute('event-index', i++)
+ }
- function increment() {
- document.getElementsByTagName('script')[0].setAttribute("event-index", i++)
- }
-
- increment()
-</script>
+ increment()
+ </script>
</html>
diff --git a/tracker/test/fixtures/engagement.html b/tracker/test/fixtures/engagement.html
index 94a0ed45a8..148af9cb9b 100644
--- a/tracker/test/fixtures/engagement.html
+++ b/tracker/test/fixtures/engagement.html
@@ -1,25 +1,25 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.local.js"></script>
+ </head>
-<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 async src="/tracker/js/plausible.local.js"></script>
-</head>
+ <body>
+ <a id="navigate-away" href="/manual.html">Navigate away</a>
+ <a id="to-pageleave-pageview-props" href="/engagement-pageview-props.html"
+ >Navigate to pageleave-pageview props</a
+ >
-<body>
- <a id="navigate-away" href="/manual.html">Navigate away</a>
- <a id="to-pageleave-pageview-props" href="/engagement-pageview-props.html">Navigate to pageleave-pageview props</a>
-
- <button id="history-nav">Navigate with history</button>
-
- <script>
- document.getElementById('history-nav').addEventListener('click', () => {
- history.pushState({ page: 2 }, 'Another Page', '/another-page');
- });
- </script>
-</body>
+ <button id="history-nav">Navigate with history</button>
+ <script>
+ document.getElementById('history-nav').addEventListener('click', () => {
+ history.pushState({ page: 2 }, 'Another Page', '/another-page')
+ })
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/file-download-plausible-web.html b/tracker/test/fixtures/file-download-plausible-web.html
index 75b47d64c1..0e929c69a7 100644
--- a/tracker/test/fixtures/file-download-plausible-web.html
+++ b/tracker/test/fixtures/file-download-plausible-web.html
@@ -1,27 +1,36 @@
-<!DOCTYPE html>
+<!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-web.js tests</title>
+ </head>
-<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-web.js tests</title>
-</head>
+ <body>
+ <a id="file-download" href="https://awesome.website.com/file.pdf"
+ >Download</a
+ >
+ <a id="file-download-iso" href="https://awesome.website.com/file.iso"
+ >Download ISO</a
+ >
-<body>
- <a id="file-download" href="https://awesome.website.com/file.pdf">Download</a>
- <a id="file-download-iso" href="https://awesome.website.com/file.iso">Download ISO</a>
+ <script>
+ window.plausible =
+ window.plausible ||
+ function () {
+ ;(window.plausible.q = window.plausible.q || []).push(arguments)
+ }
+ window.plausible.init = function (overrides) {
+ window.plausible.o = overrides || {}
+ }
- <script>
- window.plausible=window.plausible||function(){(window.plausible.q = window.plausible.q || []).push(arguments)}
- window.plausible.init = function(overrides) { window.plausible.o = overrides || {} }
+ var config = { domain: 'example.com' }
- var config = { domain: 'example.com' }
-
- const script = document.createElement('script')
- script.src = `/tracker/js/plausible-web.js?script_config=${encodeURIComponent(JSON.stringify(config))}`
- var r = document.getElementsByTagName("script")[0]
- r.parentNode.insertBefore(script, r)
- </script>
-</body>
+ const script = document.createElement('script')
+ script.src = `/tracker/js/plausible-web.js?script_config=${encodeURIComponent(JSON.stringify(config))}`
+ var r = document.getElementsByTagName('script')[0]
+ r.parentNode.insertBefore(script, r)
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/legacy-custom-properties.html b/tracker/test/fixtures/legacy-custom-properties.html
index e4ea2376c5..479bf4a2a8 100644
--- a/tracker/test/fixtures/legacy-custom-properties.html
+++ b/tracker/test/fixtures/legacy-custom-properties.html
@@ -1,16 +1,25 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.local.pageview-props.js"></script>
+ </head>
-<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 async src="/tracker/js/plausible.local.pageview-props.js"></script>
-</head>
-
-<body>
- <button id="custom-props-button" onclick="plausible('Props event', { props: { type: 'props' } })">Custom props</button>
- <button id="custom-meta-button" onclick="plausible('Meta event', { meta: { type: 'meta' } })">Custom meta</button>
-</body>
+ <body>
+ <button
+ id="custom-props-button"
+ onclick="plausible('Props event', { props: { type: 'props' } })"
+ >
+ Custom props
+ </button>
+ <button
+ id="custom-meta-button"
+ onclick="plausible('Meta event', { meta: { type: 'meta' } })"
+ >
+ Custom meta
+ </button>
+ </body>
</html>
diff --git a/tracker/test/fixtures/legacy-pageview-properties.html b/tracker/test/fixtures/legacy-pageview-properties.html
index cf0bdc6abc..140168d250 100644
--- a/tracker/test/fixtures/legacy-pageview-properties.html
+++ b/tracker/test/fixtures/legacy-pageview-properties.html
@@ -1,15 +1,24 @@
-<!DOCTYPE html>
+<!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
+ async
+ event-author="John"
+ event-foo="bar"
+ src="/tracker/js/plausible.local.pageview-props.js"
+ ></script>
+ </head>
-<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 async event-author="John" event-foo="bar" src="/tracker/js/plausible.local.pageview-props.js"></script>
-</head>
-
-<body>
- <button id="custom-event-button" onclick="plausible('Custom event', { props: { author: 'Karl' } })">Custom event</button>
-</body>
+ <body>
+ <button
+ id="custom-event-button"
+ onclick="plausible('Custom event', { props: { author: 'Karl' } })"
+ >
+ Custom event
+ </button>
+ </body>
</html>
diff --git a/tracker/test/fixtures/manual.html b/tracker/test/fixtures/manual.html
index 2c319337ea..ae36340262 100644
--- a/tracker/test/fixtures/manual.html
+++ b/tracker/test/fixtures/manual.html
@@ -1,44 +1,46 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.local.manual.js"></script>
+ </head>
-<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 async src="/tracker/js/plausible.local.manual.js"></script>
-</head>
-
-<body>
- <button id="pageview-trigger">
- Triggers a pageview with default URL (location.href)
- </button>
- <button id="pageview-trigger-custom-url">
- Triggers a pageview with custom URL
- </button>
- <button id="custom-event-trigger">
- Triggers a custom event with default URL (location.href)
- </button>
- <button id="custom-event-trigger-custom-url">
- Triggers a custom event with custom URL
- </button>
-
- <script>
- document.addEventListener('click', (e) => {
- if (e.target.id === 'pageview-trigger') {
- window.plausible('pageview')
- }
- if (e.target.id === 'pageview-trigger-custom-url') {
- window.plausible('pageview', {u: 'https://example.com/custom/location'})
- }
- if (e.target.id === 'custom-event-trigger') {
- window.plausible('CustomEvent')
- }
- if (e.target.id === 'custom-event-trigger-custom-url') {
- window.plausible('CustomEvent', {u: 'https://example.com/custom/location'})
- }
- })
- </script>
-</body>
+ <body>
+ <button id="pageview-trigger">
+ Triggers a pageview with default URL (location.href)
+ </button>
+ <button id="pageview-trigger-custom-url">
+ Triggers a pageview with custom URL
+ </button>
+ <button id="custom-event-trigger">
+ Triggers a custom event with default URL (location.href)
+ </button>
+ <button id="custom-event-trigger-custom-url">
+ Triggers a custom event with custom URL
+ </button>
+ <script>
+ document.addEventListener('click', (e) => {
+ if (e.target.id === 'pageview-trigger') {
+ window.plausible('pageview')
+ }
+ if (e.target.id === 'pageview-trigger-custom-url') {
+ window.plausible('pageview', {
+ u: 'https://example.com/custom/location'
+ })
+ }
+ if (e.target.id === 'custom-event-trigger') {
+ window.plausible('CustomEvent')
+ }
+ if (e.target.id === 'custom-event-trigger-custom-url') {
+ window.plausible('CustomEvent', {
+ u: 'https://example.com/custom/location'
+ })
+ }
+ })
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/no-async.html b/tracker/test/fixtures/no-async.html
index d119866c09..96c566410d 100644
--- a/tracker/test/fixtures/no-async.html
+++ b/tracker/test/fixtures/no-async.html
@@ -1,16 +1,14 @@
-<!DOCTYPE html>
+<!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 src="/tracker/js/plausible.local.js"></script>
+ </head>
-<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 src="/tracker/js/plausible.local.js"></script>
-</head>
-
-<body>
- HELLO!
-</body>
-
+ <body>
+ HELLO!
+ </body>
</html>
diff --git a/tracker/test/fixtures/revenue.html b/tracker/test/fixtures/revenue.html
index 2700c5c957..d586c815e0 100644
--- a/tracker/test/fixtures/revenue.html
+++ b/tracker/test/fixtures/revenue.html
@@ -1,22 +1,30 @@
-<!DOCTYPE html>
+<!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>
-<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
+ async
+ src="/tracker/js/plausible.local.manual.revenue.tagged-events.js"
+ ></script>
+ </head>
- <script async src="/tracker/js/plausible.local.manual.revenue.tagged-events.js"></script>
-</head>
+ <body>
+ <button
+ id="manual-purchase"
+ onclick="window.plausible('Purchase', {revenue: {amount: 15.99, currency: 'USD'}})"
+ >
+ Click me
+ </button>
-<body>
- <button id="manual-purchase" onclick="window.plausible('Purchase', {revenue: {amount: 15.99, currency: 'USD'}})">
- Click me
- </button>
-
- <button id="tagged-purchase" class="plausible-event-name=Purchase plausible-revenue-currency=EUR plausible-revenue-amount=13.32">
- Click me
- </button>
-</body>
+ <button
+ id="tagged-purchase"
+ class="plausible-event-name=Purchase plausible-revenue-currency=EUR plausible-revenue-amount=13.32"
+ >
+ Click me
+ </button>
+ </body>
</html>
diff --git a/tracker/test/fixtures/scroll-depth-content-onscroll.html b/tracker/test/fixtures/scroll-depth-content-onscroll.html
index 733872b2d2..21f3a9066d 100644
--- a/tracker/test/fixtures/scroll-depth-content-onscroll.html
+++ b/tracker/test/fixtures/scroll-depth-content-onscroll.html
@@ -1,35 +1,40 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.local.js"></script>
+ </head>
-<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 async src="/tracker/js/plausible.local.js"></script>
-</head>
+ <body>
+ <div id="main" style="height: 3000px; background-color: lightblue">
+ <a id="navigate-away" href="/manual.html">Navigate away</a>
+ </div>
-<body>
- <div id="main" style="height: 3000px; background-color: lightblue;">
- <a id="navigate-away" href="/manual.html">Navigate away</a>
- </div>
+ <script>
+ document.addEventListener('DOMContentLoaded', () => {
+ const mainDiv = document.getElementById('main')
+ let loadedMore = false
- <script>
- document.addEventListener("DOMContentLoaded", () => {
- const mainDiv = document.getElementById("main")
- let loadedMore = false
+ window.addEventListener('scroll', () => {
+ if (
+ !loadedMore &&
+ window.innerHeight + window.scrollY >= document.body.offsetHeight
+ ) {
+ loadedMore = true
- window.addEventListener("scroll", () => {
- if (!loadedMore && window.innerHeight + window.scrollY >= document.body.offsetHeight) {
- loadedMore = true
-
- const newDiv = document.createElement("div")
- newDiv.setAttribute("id", "more-content")
- newDiv.setAttribute("style", "height: 2000px; background-color: lightcoral;")
- document.body.appendChild(newDiv);
- }
- });
- });
- </script>
-</body>
+ const newDiv = document.createElement('div')
+ newDiv.setAttribute('id', 'more-content')
+ newDiv.setAttribute(
+ 'style',
+ 'height: 2000px; background-color: lightcoral;'
+ )
+ document.body.appendChild(newDiv)
+ }
+ })
+ })
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/scroll-depth-dynamic-content-load.html b/tracker/test/fixtures/scroll-depth-dynamic-content-load.html
index 708e1d96ef..bd0f3651e4 100644
--- a/tracker/test/fixtures/scroll-depth-dynamic-content-load.html
+++ b/tracker/test/fixtures/scroll-depth-dynamic-content-load.html
@@ -1,25 +1,24 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <script async src="/tracker/js/plausible.local.js"></script>
-</head>
-<body>
- <br>
- <div id="content"></div>
- <script>
- setTimeout(() => {
- document.getElementById('content').innerHTML =
- `
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Document</title>
+ <script async src="/tracker/js/plausible.local.js"></script>
+ </head>
+ <body>
+ <br />
+ <div id="content"></div>
+ <script>
+ setTimeout(() => {
+ document.getElementById('content').innerHTML = `
<div style="height: 5000px; background-color: gray;">
<a id="navigate-away" href="/manual.html">
Navigate away
</a>
</div>
`
- }, 500)
- </script>
-</body>
+ }, 500)
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/scroll-depth-hash.html b/tracker/test/fixtures/scroll-depth-hash.html
index d364f302c1..4762883df9 100644
--- a/tracker/test/fixtures/scroll-depth-hash.html
+++ b/tracker/test/fixtures/scroll-depth-hash.html
@@ -1,37 +1,36 @@
-<!DOCTYPE html>
+<!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 async src="/tracker/js/plausible.hash.local.js"></script>
+ </head>
-<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 async src="/tracker/js/plausible.hash.local.js"></script>
-</head>
+ <body>
+ <nav>
+ <a id="home-link" href="#home">Home</a>
+ <a id="about-link" href="#about">About</a>
+ </nav>
-<body>
- <nav>
- <a id="home-link" href="#home">Home</a>
- <a id="about-link" href="#about">About</a>
- </nav>
+ <div id="content"></div>
- <div id="content"></div>
+ <script>
+ const routes = {
+ '#home': '<h1>Home</h1><p>Welcome to the Home page!</p>',
+ '#about':
+ '<h1>About</h1><p style="height: 2000px;">Learn more about us here</p>'
+ }
- <script>
- const routes = {
- '#home': '<h1>Home</h1><p>Welcome to the Home page!</p>',
- '#about': '<h1>About</h1><p style="height: 2000px;">Learn more about us here</p>',
- };
-
- function loadContent() {
- const hash = window.location.hash || '#home';
- const content = routes[hash]
- document.getElementById('content').innerHTML = content;
- }
-
- window.addEventListener('hashchange', loadContent);
- window.addEventListener('DOMContentLoaded', loadContent);
- </script>
-</body>
+ function loadContent() {
+ const hash = window.location.hash || '#home'
+ const content = routes[hash]
+ document.getElementById('content').innerHTML = content
+ }
+ window.addEventListener('hashchange', loadContent)
+ window.addEventListener('DOMContentLoaded', loadContent)
+ </script>
+ </body>
</html>
diff --git a/tracker/test/fixtures/scroll-depth-slow-window-load.html b/tracker/test/fixtures/scroll-depth-slow-window-load.html
index e043c666cd..ed81e705ba 100644
--- a/tracker/test/fixtures/scroll-depth-slow-window-load.html
+++ b/tracker/test/fixtures/scroll-depth-slow-window-load.html
@@ -1,16 +1,14 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <script async src="/tracker/js/plausible.local.js"></script>
-</head>
-<body>
- <a id="navigate-away" href="/manual.html">
- Navigate away
- </a>
- <br>
- <img id="slow-image" src="/img/slow-image" alt="slow image">
-</body>
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Document</title>
+ <script async src="/tracker/js/plausible.local.js"></script>
+ </head>
+ <body>
+ <a id="navigate-away" href="/manual.html"> Navigate away </a>
+ <br />
+ <img id="slow-image" src="/img/slow-image" alt="slow image" />
+ </body>
</html>
diff --git a/tracker/test/fixtures/scroll-depth.html b/tracker/test/fixtures/scroll-depth.html
index 5db9e9e587..ef6923abca 100644
--- a/tracker/test/fixtures/scroll-depth.html
+++ b/tracker/test/fixtures/scroll-depth.html
@@ -1,14 +1,19 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <script async src="/tracker/js/plausible.local.js"></script>
- <title>Document</title>
-</head>
-<body>
- <div style="height: 5000px; background: repeating-linear-gradient(white, gray 500px);">
- <a id="navigate-away" href="/manual.html">Navigate away</a>
- </div>
-</body>
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <script async src="/tracker/js/plausible.local.js"></script>
+ <title>Document</title>
+ </head>
+ <body>
+ <div
+ style="
+ height: 5000px;
+ background: repeating-linear-gradient(white, gray 500px);
+ "
+ >
+ <a id="navigate-away" href="/manual.html">Navigate away</a>
+ </div>
+ </body>
</html>
diff --git a/tracker/test/form-submissions.spec.ts b/tracker/test/form-submissions.spec.ts
index 4dd26ae58d..24c5c66d71 100644
--- a/tracker/test/form-submissions.spec.ts
+++ b/tracker/test/form-submissions.spec.ts
@@ -23,10 +23,8 @@ test('does not track form submissions when the feature is disabled', async ({
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: DEFAULT_CONFIG,
- bodyContent: `
- <form>
- <input type="text" /><input type="submit" value="Submit" />
- </form>
+ bodyContent: /* HTML */ `
+ <form><input type="text" /><input type="submit" value="Submit" /></form>
`
})
@@ -50,9 +48,12 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
+ bodyContent: /* HTML */ `
<form method="GET">
- <input id="name" type="text" placeholder="Name" /><input type="submit" value="Submit" />
+ <input id="name" type="text" placeholder="Name" /><input
+ type="submit"
+ value="Submit"
+ />
</form>
`
})
@@ -81,8 +82,8 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
- <form onsubmit="${customSubmitHandlerStub}">
+ bodyContent: /* HTML */ `
+ <form onsubmit=${customSubmitHandlerStub}>
<input type="text" /><input type="submit" value="Submit" />
</form>
`
@@ -109,21 +110,24 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
- <div>
- <button id="dynamically-insert-form" onclick="createForm()">Open form</button>
- <script>
- function createForm() {
- const form = document.createElement('form');
- form.setAttribute('onsubmit', "${customSubmitHandlerStub}");
- const submit = document.createElement('input');
- submit.type = 'submit';
- submit.value = 'Submit';
- form.appendChild(submit);
- document.body.appendChild(form);
- }
- </script>
- </div>
+ bodyContent: /* HTML */ `
+ <div>
+ <button id="dynamically-insert-form" onclick="createForm()">
+ Open form
+ </button>
+ <script>
+ function createForm() {
+ const form = document.createElement('form')
+ /* prettier-ignore */
+ form.onsubmit = ${customSubmitHandlerStub}
+ const submit = document.createElement('input')
+ submit.type = 'submit'
+ submit.value = 'Submit'
+ form.appendChild(submit)
+ document.body.appendChild(form)
+ }
+ </script>
+ </div>
`
})
@@ -151,8 +155,8 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
- <form novalidate onsubmit="${customSubmitHandlerStub}">
+ bodyContent: /* HTML */ `
+ <form novalidate onsubmit=${customSubmitHandlerStub}>
<input type="email" />
<input type="submit" value="Submit" />
</form>
@@ -184,7 +188,7 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
+ bodyContent: /* HTML */ `
<form>
<input type="email" />
<input type="submit" value="Submit" />
@@ -215,11 +219,16 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
+ bodyContent: /* HTML */ `
<form id="form">
<input type="text" placeholder="Name" />
</form>
- <button id="trigger-FormElement-submit" onclick="document.getElementById('form').submit()">Submit</button>
+ <button
+ id="trigger-FormElement-submit"
+ onclick="document.getElementById('form').submit()"
+ >
+ Submit
+ </button>
`
})
@@ -246,12 +255,12 @@ test.describe('form submissions feature is enabled', () => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: { ...DEFAULT_CONFIG, formSubmissions: true },
- bodyContent: `
- <form onsubmit="${customSubmitHandlerStub}">
+ bodyContent: /* HTML */ `
+ <form onsubmit=${customSubmitHandlerStub}>
<h2>Form 1</h2>
<input type="text" /><input type="submit" value="Submit" />
</form>
- <form onsubmit="${customSubmitHandlerStub}">
+ <form onsubmit=${customSubmitHandlerStub}>
<h2>Form 2</h2>
<input type="email" />
</form>
diff --git a/tracker/test/hash-based-routing.spec.ts b/tracker/test/hash-based-routing.spec.ts
index d9fda649ec..b6ab29a121 100644
--- a/tracker/test/hash-based-routing.spec.ts
+++ b/tracker/test/hash-based-routing.spec.ts
@@ -3,7 +3,7 @@ import {
e,
expectPlausibleInAction,
hideAndShowCurrentTab,
- switchByMode,
+ switchByMode
} from './support/test-utils'
import { test } from '@playwright/test'
import { ScriptConfig } from './support/types'
@@ -95,7 +95,11 @@ test.describe('hash-based routing (legacy)', () => {
}, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script data-domain="${DEFAULT_CONFIG.domain}" async src="/tracker/js/plausible.hash.local.js"></script>`,
+ scriptConfig: /* HTML */ `<script
+ data-domain="${DEFAULT_CONFIG.domain}"
+ async
+ src="/tracker/js/plausible.hash.local.js"
+ ></script>`,
bodyContent: ''
})
diff --git a/tracker/test/hash-exclusions.spec.ts b/tracker/test/hash-exclusions.spec.ts
index e4d2c342f9..288f1253b7 100644
--- a/tracker/test/hash-exclusions.spec.ts
+++ b/tracker/test/hash-exclusions.spec.ts
@@ -6,7 +6,11 @@ test.describe('combination of hash and exclusions script extensions', () => {
test('excludes by hash part of the URL', async ({ page }, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-exclude='/**#*/hash/**/ignored' src="/tracker/js/plausible.exclusions.hash.local.js"></script>`,
+ scriptConfig: /* HTML */ `<script
+ async
+ data-exclude="/**#*/hash/**/ignored"
+ src="/tracker/js/plausible.exclusions.hash.local.js"
+ ></script>`,
bodyContent: ''
})
await expectPlausibleInAction(page, {
diff --git a/tracker/test/installation_support/check-data-domain-mismatch.spec.js b/tracker/test/installation_support/check-data-domain-mismatch.spec.js
index bccb12a0fd..b7603dc1d2 100644
--- a/tracker/test/installation_support/check-data-domain-mismatch.spec.js
+++ b/tracker/test/installation_support/check-data-domain-mismatch.spec.js
@@ -2,7 +2,7 @@ import { test, expect } from '@playwright/test'
import { checkDataDomainMismatch } from '../../installation_support/check-data-domain-mismatch'
function mockSnippet(dataDomain) {
- return { getAttribute: _ => dataDomain }
+ return { getAttribute: (_) => dataDomain }
}
test.describe('checkDataDomainMismatch', () => {
@@ -43,7 +43,9 @@ test.describe('checkDataDomainMismatch', () => {
})
test('handles multiple domains with www prefix', () => {
- const snippets = [mockSnippet('www.example.org, www.example.com, www.example.net')]
+ const snippets = [
+ mockSnippet('www.example.org, www.example.com, www.example.net')
+ ]
expect(checkDataDomainMismatch(snippets, 'example.com')).toBe(false)
})
@@ -53,10 +55,7 @@ test.describe('checkDataDomainMismatch', () => {
})
test('handles multiple snippets - returns true if any snippet has domain mismatch', () => {
- const snippets = [
- mockSnippet('example.com'),
- mockSnippet('wrong.com')
- ]
+ const snippets = [mockSnippet('example.com'), mockSnippet('wrong.com')]
expect(checkDataDomainMismatch(snippets, 'example.com')).toBe(true)
})
@@ -67,4 +66,4 @@ test.describe('checkDataDomainMismatch', () => {
]
expect(checkDataDomainMismatch(snippets, 'example.com')).toBe(false)
})
-})
\ No newline at end of file
+})
diff --git a/tracker/test/installation_support/check-disallowed-by-csp.spec.js b/tracker/test/installation_support/check-disallowed-by-csp.spec.js
index 963077d7f2..ac15b04aef 100644
--- a/tracker/test/installation_support/check-disallowed-by-csp.spec.js
+++ b/tracker/test/installation_support/check-disallowed-by-csp.spec.js
@@ -6,35 +6,49 @@ const HOST_TO_CHECK = 'plausible.io'
test.describe('checkDisallowedByCSP', () => {
test('returns false if no CSP header', () => {
expect(checkDisallowedByCSP({}, HOST_TO_CHECK)).toBe(false)
- expect(checkDisallowedByCSP({foo: 'bar'}, HOST_TO_CHECK)).toBe(false)
+ expect(checkDisallowedByCSP({ foo: 'bar' }, HOST_TO_CHECK)).toBe(false)
})
test('returns false if CSP header is empty', () => {
- expect(checkDisallowedByCSP({'content-security-policy': ''}, HOST_TO_CHECK)).toBe(false)
+ expect(
+ checkDisallowedByCSP({ 'content-security-policy': '' }, HOST_TO_CHECK)
+ ).toBe(false)
})
test('returns true if plausible.io is not allowed', () => {
- const headers = {'content-security-policy': "default-src 'self' foo.local; example.com"}
+ const headers = {
+ 'content-security-policy': "default-src 'self' foo.local; example.com"
+ }
expect(checkDisallowedByCSP(headers, HOST_TO_CHECK)).toBe(true)
})
test('returns false if plausible.io is allowed', () => {
- const headers = {'content-security-policy': "default-src 'self' plausible.io; example.com"}
+ const headers = {
+ 'content-security-policy': "default-src 'self' plausible.io; example.com"
+ }
expect(checkDisallowedByCSP(headers, HOST_TO_CHECK)).toBe(false)
})
test('returns false if plausible.io subdomain is allowed', () => {
- const headers = {'content-security-policy': "default-src 'self' staging.plausible.io; example.com"}
+ const headers = {
+ 'content-security-policy':
+ "default-src 'self' staging.plausible.io; example.com"
+ }
expect(checkDisallowedByCSP(headers, HOST_TO_CHECK)).toBe(false)
})
test('returns false if plausible.io is allowed with https', () => {
- const headers = {'content-security-policy': "default-src 'self' https://plausible.io; example.com"}
+ const headers = {
+ 'content-security-policy':
+ "default-src 'self' https://plausible.io; example.com"
+ }
expect(checkDisallowedByCSP(headers, HOST_TO_CHECK)).toBe(false)
})
test('returns true if plausible.io is not present in any directive', () => {
- const headers = {'content-security-policy': "default-src 'self' foo.com; bar.com"}
+ const headers = {
+ 'content-security-policy': "default-src 'self' foo.com; bar.com"
+ }
expect(checkDisallowedByCSP(headers, HOST_TO_CHECK)).toBe(true)
})
-})
\ No newline at end of file
+})
diff --git a/tracker/test/installation_support/check-gtm.spec.js b/tracker/test/installation_support/check-gtm.spec.js
index 2bda508e41..d684dd9796 100644
--- a/tracker/test/installation_support/check-gtm.spec.js
+++ b/tracker/test/installation_support/check-gtm.spec.js
@@ -3,7 +3,7 @@ import { checkGTM } from '../../installation_support/check-gtm'
function mockDocument(html) {
return {
- documentElement: {outerHTML: `<html>${html}</html>`}
+ documentElement: { outerHTML: `<html>${html}</html>` }
}
}
@@ -13,7 +13,7 @@ test.describe('checkGTM (gtmLikely)', () => {
})
test('handles document.documentElement undefined', () => {
- const document = {documentElement: undefined}
+ const document = { documentElement: undefined }
expect(checkGTM(document)).toBe(false)
})
@@ -23,7 +23,9 @@ test.describe('checkGTM (gtmLikely)', () => {
})
test('detects gtmLikely by googletagmanager.com/gtm.js signature', () => {
- const document = mockDocument('<head><script src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXX"></script></head>')
+ const document = mockDocument(
+ '<head><script src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXX"></script></head>'
+ )
expect(checkGTM(document)).toBe(true)
})
-})
\ No newline at end of file
+})
diff --git a/tracker/test/installation_support/check-manual-extension.spec.js b/tracker/test/installation_support/check-manual-extension.spec.js
index 3683ef54fc..798e20a20a 100644
--- a/tracker/test/installation_support/check-manual-extension.spec.js
+++ b/tracker/test/installation_support/check-manual-extension.spec.js
@@ -2,7 +2,7 @@ import { test, expect } from '@playwright/test'
import { checkManualExtension } from '../../installation_support/check-manual-extension'
function mockSnippet(dataDomain) {
- return { getAttribute: _ => dataDomain }
+ return { getAttribute: (_) => dataDomain }
}
test.describe('checkManualExtension', () => {
@@ -42,4 +42,4 @@ test.describe('checkManualExtension', () => {
]
expect(checkManualExtension(snippets)).toBe(false)
})
-})
\ No newline at end of file
+})
diff --git a/tracker/test/installation_support/check-proxy-likely.spec.js b/tracker/test/installation_support/check-proxy-likely.spec.js
index 6c620bc082..808c8e5fc4 100644
--- a/tracker/test/installation_support/check-proxy-likely.spec.js
+++ b/tracker/test/installation_support/check-proxy-likely.spec.js
@@ -2,7 +2,7 @@ import { test, expect } from '@playwright/test'
import { checkProxyLikely } from '../../installation_support/check-proxy-likely'
function mockSnippet(src) {
- return { getAttribute: _ => src }
+ return { getAttribute: (_) => src }
}
test.describe('checkProxyLikely', () => {
@@ -23,12 +23,16 @@ test.describe('checkProxyLikely', () => {
})
test('returns false when snippet src is official plausible.io URL with query params', () => {
- const snippets = [mockSnippet('https://plausible.io/js/plausible.js?v=1.0.0')]
+ const snippets = [
+ mockSnippet('https://plausible.io/js/plausible.js?v=1.0.0')
+ ]
expect(checkProxyLikely(snippets)).toBe(false)
})
test('handles similar domain names (should be true)', () => {
- const snippets = [mockSnippet('https://plausible.io.example.com/js/plausible.js')]
+ const snippets = [
+ mockSnippet('https://plausible.io.example.com/js/plausible.js')
+ ]
expect(checkProxyLikely(snippets)).toBe(true)
})
@@ -54,7 +58,9 @@ test.describe('checkProxyLikely', () => {
})
test('handles plausible.io subdomain (should be true)', () => {
- const snippets = [mockSnippet('https://staging.plausible.io/js/plausible.js')]
+ const snippets = [
+ mockSnippet('https://staging.plausible.io/js/plausible.js')
+ ]
expect(checkProxyLikely(snippets)).toBe(true)
})
-})
\ No newline at end of file
+})
diff --git a/tracker/test/installation_support/check-wp.spec.js b/tracker/test/installation_support/check-wp.spec.js
index 8523fbd7b9..2e555439ff 100644
--- a/tracker/test/installation_support/check-wp.spec.js
+++ b/tracker/test/installation_support/check-wp.spec.js
@@ -1,9 +1,12 @@
import { test, expect } from '@playwright/test'
-import { checkWordPress, WORDPRESS_PLUGIN_VERSION_SELECTOR } from '../../installation_support/check-wordpress'
+import {
+ checkWordPress,
+ WORDPRESS_PLUGIN_VERSION_SELECTOR
+} from '../../installation_support/check-wordpress'
function mockDocument(html, hasMetaTag) {
return {
- documentElement: {outerHTML: `<html>${html}</html>`},
+ documentElement: { outerHTML: `<html>${html}</html>` },
querySelector: (selector) => {
if (selector === WORDPRESS_PLUGIN_VERSION_SELECTOR) {
return hasMetaTag ? {} : null
@@ -16,23 +19,23 @@ function mockDocument(html, hasMetaTag) {
test.describe('checkWordPress (wordpressPlugin, wordPressLikely)', () => {
test('handles document undefined', () => {
const result = checkWordPress(undefined)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(false)
})
test('handles document.querySelector undefined', () => {
- const document = {documentElement: {outerHTML: '<html></html>'}}
+ const document = { documentElement: { outerHTML: '<html></html>' } }
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(false)
})
test('handles document.documentElement undefined', () => {
- const document = {documentElement: undefined, querySelector: (_) => null}
+ const document = { documentElement: undefined, querySelector: (_) => null }
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(false)
})
@@ -40,7 +43,7 @@ test.describe('checkWordPress (wordpressPlugin, wordPressLikely)', () => {
test('both false when no WordPress indicators present', () => {
const document = mockDocument('<head></head><body></body>', false)
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(false)
})
@@ -48,31 +51,40 @@ test.describe('checkWordPress (wordpressPlugin, wordPressLikely)', () => {
test('both true if WordPress plugin version meta tag detected', () => {
const document = mockDocument('<head></head><body></body>', true)
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(true)
expect(result.wordpressLikely).toBe(true)
})
test('detects wordpressLikely by wp-content signature', () => {
- const document = mockDocument('<head><script src="/wp-content/themes/mytheme/script.js"></script></head>', false)
+ const document = mockDocument(
+ '<head><script src="/wp-content/themes/mytheme/script.js"></script></head>',
+ false
+ )
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(true)
})
test('detects wordpressLikely by wp-includes signature', () => {
- const document = mockDocument('<head><link rel="stylesheet" href="/wp-includes/css/style.css"></head>', false)
+ const document = mockDocument(
+ '<head><link rel="stylesheet" href="/wp-includes/css/style.css"></head>',
+ false
+ )
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(true)
})
test('detects wordpressLikely by wp-json signature', () => {
- const document = mockDocument('<body><script>fetch("/wp-json/wp/v2/posts")</script></body>', false)
+ const document = mockDocument(
+ '<body><script>fetch("/wp-json/wp/v2/posts")</script></body>',
+ false
+ )
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(true)
})
@@ -89,10 +101,10 @@ test.describe('checkWordPress (wordpressPlugin, wordPressLikely)', () => {
`,
false
)
-
+
const result = checkWordPress(document)
-
+
expect(result.wordpressPlugin).toBe(false)
expect(result.wordpressLikely).toBe(true)
})
-})
\ No newline at end of file
+})
diff --git a/tracker/test/installation_support/detector.spec.js b/tracker/test/installation_support/detector.spec.js
index 0acdd9cb33..d980be1bfd 100644
--- a/tracker/test/installation_support/detector.spec.js
+++ b/tracker/test/installation_support/detector.spec.js
@@ -3,10 +3,12 @@ import { detect } from '../support/installation-support-playwright-wrappers'
import { initializePageDynamically } from '../support/initialize-page-dynamically'
test.describe('detector.js (tech recognition)', () => {
- test('skips v1 snippet detection by default', async ({ page }, { testId }) => {
+ test('skips v1 snippet detection by default', async ({ page }, {
+ testId
+ }) => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
<script src="" data-domain=""></script>
@@ -15,7 +17,11 @@ test.describe('detector.js (tech recognition)', () => {
`
})
- const result = await detect(page, {url: url, detectV1: false, timeoutMs: 1000})
+ const result = await detect(page, {
+ url: url,
+ detectV1: false,
+ timeoutMs: 1000
+ })
expect(result.data.v1Detected).toBe(null)
})
@@ -23,18 +29,29 @@ test.describe('detector.js (tech recognition)', () => {
test('detects WP plugin, WP and GTM', async ({ page }, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
- <link rel="icon" href="https://example.com/wp-content/uploads/favicon.ico" sizes="32x32">
- <meta name="plausible-analytics-version" content="2.3.1">
- <script async src="https://www.googletagmanager.com/gtm.js?id=GTM-123"></script>
+ <link
+ rel="icon"
+ href="https://example.com/wp-content/uploads/favicon.ico"
+ sizes="32x32"
+ />
+ <meta name="plausible-analytics-version" content="2.3.1" />
+ <script
+ async
+ src="https://www.googletagmanager.com/gtm.js?id=GTM-123"
+ ></script>
</head>
</html>
`
})
- const result = await detect(page, {url: url, detectV1: false, timeoutMs: 1000})
+ const result = await detect(page, {
+ url: url,
+ detectV1: false,
+ timeoutMs: 1000
+ })
expect(result.data.wordpressPlugin).toBe(true)
expect(result.data.wordpressLikely).toBe(true)
@@ -44,10 +61,16 @@ test.describe('detector.js (tech recognition)', () => {
test('No WP plugin, WP or GTM', async ({ page }, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- response: '<html><head></head></html>'
+ response: /* HTML */ `<html>
+ <head></head>
+ </html>`
})
- const result = await detect(page, {url: url, detectV1: false, timeoutMs: 1000})
+ const result = await detect(page, {
+ url: url,
+ detectV1: false,
+ timeoutMs: 1000
+ })
expect(result.data.wordpressPlugin).toBe(false)
expect(result.data.wordpressLikely).toBe(false)
@@ -58,10 +81,13 @@ test.describe('detector.js (tech recognition)', () => {
test('npm is reported correctly', async ({ page }, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import {init} from "/tracker/js/npm_package/plausible.js"; init({domain: "abc.de"});</script>`
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init } from '/tracker/js/npm_package/plausible.js'
+ init({ domain: 'abc.de' })
+ </script>`
})
- const result = await detect(page, {url: url, detectV1: false})
+ const result = await detect(page, { url: url, detectV1: false })
expect(result.data.wordpressPlugin).toBe(false)
expect(result.data.wordpressLikely).toBe(false)
@@ -71,22 +97,39 @@ test.describe('detector.js (tech recognition)', () => {
})
test.describe('detector.js (v1 detection)', () => {
- test('v1Detected is true when v1 plausible exists + detects WP plugin, WP and GTM', async ({ page }, { testId }) => {
+ test('v1Detected is true when v1 plausible exists + detects WP plugin, WP and GTM', async ({
+ page
+ }, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
- <link rel="icon" href="https://example.com/wp-content/uploads/favicon.ico" sizes="32x32">
- <meta name="plausible-analytics-version" content="2.3.1">
- <script async src="https://www.googletagmanager.com/gtm.js?id=GTM-123"></script>
- <script async src="/tracker/js/plausible.local.manual.js" data-domain="abc.de"></script>
+ <link
+ rel="icon"
+ href="https://example.com/wp-content/uploads/favicon.ico"
+ sizes="32x32"
+ />
+ <meta name="plausible-analytics-version" content="2.3.1" />
+ <script
+ async
+ src="https://www.googletagmanager.com/gtm.js?id=GTM-123"
+ ></script>
+ <script
+ async
+ src="/tracker/js/plausible.local.manual.js"
+ data-domain="abc.de"
+ ></script>
</head>
</html>
`
})
- const result = await detect(page, {url: url, detectV1: true, timeoutMs: 1000})
+ const result = await detect(page, {
+ url: url,
+ detectV1: true,
+ timeoutMs: 1000
+ })
expect(result.data.v1Detected).toBe(true)
expect(result.data.wordpressPlugin).toBe(true)
@@ -95,13 +138,21 @@ test.describe('detector.js (v1 detection)', () => {
expect(result.data.npm).toBe(false)
})
- test('v1Detected is false when plausible function does not exist', async ({ page }, { testId }) => {
+ test('v1Detected is false when plausible function does not exist', async ({
+ page
+ }, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- response: '<html><head></head></html>'
+ response: /* HTML */ `<html>
+ <head></head>
+ </html>`
})
- const result = await detect(page, {url: url, detectV1: true, timeoutMs: 1000})
+ const result = await detect(page, {
+ url: url,
+ detectV1: true,
+ timeoutMs: 1000
+ })
expect(result.data.v1Detected).toBe(false)
expect(result.data.wordpressPlugin).toBe(false)
@@ -110,7 +161,9 @@ test.describe('detector.js (v1 detection)', () => {
expect(result.data.npm).toBe(false)
})
- test('v1Detected is false when v2 plausible installed', async ({ page }, { testId }) => {
+ test('v1Detected is false when v2 plausible installed', async ({ page }, {
+ testId
+ }) => {
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: {
@@ -119,7 +172,11 @@ test.describe('detector.js (v1 detection)', () => {
}
})
- const result = await detect(page, {url: url, detectV1: true, timeoutMs: 1000})
+ const result = await detect(page, {
+ url: url,
+ detectV1: true,
+ timeoutMs: 1000
+ })
expect(result.data.v1Detected).toBe(false)
})
diff --git a/tracker/test/installation_support/verifier-v1.spec.js b/tracker/test/installation_support/verifier-v1.spec.js
index 779f44c8a7..b68cd354c0 100644
--- a/tracker/test/installation_support/verifier-v1.spec.js
+++ b/tracker/test/installation_support/verifier-v1.spec.js
@@ -26,10 +26,17 @@ test.describe('v1 verifier (basic diagnostics)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.snippetsFoundInHead).toBe(1)
@@ -52,27 +59,31 @@ test.describe('v1 verifier (basic diagnostics)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
- <html>
- <head></head>
- <body>
- <script>
- const script = document.createElement('script')
+ response: /* HTML */ `
+ <html>
+ <head></head>
+ <body>
+ <script>
+ const script = document.createElement('script')
- script.async = true
- script.dataset.domain = '${SOME_DOMAIN}'
- script.src = "/tracker/js/plausible.local.manual.js"
+ script.async = true
+ script.dataset.domain = '${SOME_DOMAIN}'
+ script.src = '/tracker/js/plausible.local.manual.js'
- setTimeout(() => {
- document.getElementsByTagName('head')[0].appendChild(script)
- }, 500)
- </script>
- </body>
- </html>
+ setTimeout(() => {
+ document.getElementsByTagName('head')[0].appendChild(script)
+ }, 500)
+ </script>
+ </body>
+ </html>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN, debug: true})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN,
+ debug: true
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.snippetsFoundInHead).toBe(1)
@@ -87,7 +98,10 @@ test.describe('v1 verifier (basic diagnostics)', () => {
scriptConfig: ''
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.plausibleInstalled).toBe(false)
expect(result.data.callbackStatus).toBe(0)
@@ -101,10 +115,19 @@ test.describe('v1 verifier (basic diagnostics)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `<body><script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script></body>`
+ response: /* HTML */ `<body>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ </body>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.snippetsFoundInHead).toBe(0)
@@ -113,15 +136,26 @@ test.describe('v1 verifier (basic diagnostics)', () => {
expect(result.data.dataDomainMismatch).toBe(false)
})
- test('figures out well placed snippet in a multi-domain setup', async ({ page }, { testId }) => {
+ test('figures out well placed snippet in a multi-domain setup', async ({
+ page
+ }, { testId }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `<head><script async data-domain="example.org,example.com,example.net" src="/tracker/js/plausible.local.js"></script></head>`
+ response: /* HTML */ `<head>
+ <script
+ async
+ data-domain="example.org,example.com,example.net"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ </head>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: "example.com"})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: 'example.com'
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.snippetsFoundInHead).toBe(1)
@@ -130,15 +164,26 @@ test.describe('v1 verifier (basic diagnostics)', () => {
expect(result.data.dataDomainMismatch).toBe(false)
})
- test('figures out well placed snippet in a multi-domain mismatch', async ({ page }, { testId }) => {
+ test('figures out well placed snippet in a multi-domain mismatch', async ({
+ page
+ }, { testId }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `<head><script async data-domain="example.org,example.com,example.net" src="/tracker/js/plausible.local.js"></script></head>`
+ response: /* HTML */ `<head>
+ <script
+ async
+ data-domain="example.org,example.com,example.net"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ </head>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: "example.typo"})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: 'example.typo'
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.snippetsFoundInHead).toBe(1)
@@ -147,20 +192,25 @@ test.describe('v1 verifier (basic diagnostics)', () => {
expect(result.data.dataDomainMismatch).toBe(true)
})
- test('proxyLikely is false when every snippet starts with an official plausible.io URL', async ({ page }, { testId }) => {
+ test('proxyLikely is false when every snippet starts with an official plausible.io URL', async ({
+ page
+ }, { testId }) => {
const prodScriptLocation = 'https://plausible.io/js/'
mockEventResponseSuccess(page)
// We speed up the test by serving "just some script"
// (avoiding the event callback delay in verifier)
- const code = await compileFile({
- name: "plausible.local.js",
- globals: {
- "COMPILE_LOCAL": true,
- "COMPILE_PLAUSIBLE_LEGACY_VARIANT": true
- }
- }, { returnCode: true })
+ const code = await compileFile(
+ {
+ name: 'plausible.local.js',
+ globals: {
+ COMPILE_LOCAL: true,
+ COMPILE_PLAUSIBLE_LEGACY_VARIANT: true
+ }
+ },
+ { returnCode: true }
+ )
await page.context().route(`${prodScriptLocation}**`, async (route) => {
await route.fulfill({
@@ -172,13 +222,28 @@ test.describe('v1 verifier (basic diagnostics)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
- <head><script async src="${prodScriptLocation + 'script.js'}" data-domain="${SOME_DOMAIN}"></script></head>
- <body><script async src="${prodScriptLocation + 'plausible.outbound-links.js'}" data-domain="${SOME_DOMAIN}"></script></body>
+ response: /* HTML */ `
+ <head>
+ <script
+ async
+ src="${prodScriptLocation + 'script.js'}"
+ data-domain="${SOME_DOMAIN}"
+ ></script>
+ </head>
+ <body>
+ <script
+ async
+ src="${prodScriptLocation + 'plausible.outbound-links.js'}"
+ data-domain="${SOME_DOMAIN}"
+ ></script>
+ </body>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.proxyLikely).toBe(false)
})
@@ -188,20 +253,43 @@ test.describe('v1 verifier (basic diagnostics)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<head>
- <script async data-domain="example.com" src="/tracker/js/plausible.local.js"></script>
- <script async data-domain="example.com" src="/tracker/js/plausible.local.js"></script>
+ <script
+ async
+ data-domain="example.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ <script
+ async
+ data-domain="example.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>
</head>
<body>
- <script async data-domain="example.com" src="/tracker/js/plausible.local.js"></script>
- <script async data-domain="example.com" src="/tracker/js/plausible.local.js"></script>
- <script async data-domain="example.com" src="/tracker/js/plausible.local.js"></script>
+ <script
+ async
+ data-domain="example.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ <script
+ async
+ data-domain="example.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ <script
+ async
+ data-domain="example.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>
</body>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: "example.com"})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: 'example.com'
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.snippetsFoundInHead).toBe(2)
@@ -215,71 +303,113 @@ test.describe('v1 verifier (basic diagnostics)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="wrong.com" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="wrong.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: 'right.com'})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: 'right.com'
+ })
expect(result.data.dataDomainMismatch).toBe(true)
})
- test('dataDomainMismatch is false when data-domain without "www." prefix matches', async ({ page }, { testId }) => {
+ test('dataDomainMismatch is false when data-domain without "www." prefix matches', async ({
+ page
+ }, { testId }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="www.right.com" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="www.right.com"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: 'right.com'})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: 'right.com'
+ })
expect(result.data.dataDomainMismatch).toBe(false)
})
-
})
test.describe('v1 verifier (window.plausible)', () => {
- test('callbackStatus is 404 when /api/event not found', async ({ page }, { testId }) => {
+ test('callbackStatus is 404 when /api/event not found', async ({ page }, {
+ testId
+ }) => {
await page.context().route('**/api/event', async (route) => {
- await route.fulfill({status: 404})
+ await route.fulfill({ status: 404 })
})
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.callbackStatus).toBe(404)
})
- test('callBackStatus is 0 when event request times out', async ({ page }, { testId }) => {
+ test('callBackStatus is 0 when event request times out', async ({ page }, {
+ testId
+ }) => {
mockEventResponseSuccess(page, 20000)
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.callbackStatus).toBe(0)
})
- test('callBackStatus is -1 when a network error occurs on sending event', async ({ page }, { testId }) => {
+ test('callBackStatus is -1 when a network error occurs on sending event', async ({
+ page
+ }, { testId }) => {
await page.context().route('**/api/event', async (route) => {
await route.abort()
})
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.plausibleInstalled).toBe(true)
expect(result.data.callbackStatus).toBe(-1)
@@ -287,33 +417,48 @@ test.describe('v1 verifier (window.plausible)', () => {
})
test.describe('v1 verifier (WordPress detection)', () => {
- test('if wordpress plugin detected, wordpressLikely is also true', async ({ page }, { testId }) => {
+ test('if wordpress plugin detected, wordpressLikely is also true', async ({
+ page
+ }, { testId }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<head>
- <meta name="plausible-analytics-version" content="2.3.1">
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>
+ <meta name="plausible-analytics-version" content="2.3.1" />
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>
</head>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.wordpressPlugin).toBe(true)
expect(result.data.wordpressLikely).toBe(true)
})
- test('detects wordpressLikely by wp signatures', async ({ page }, { testId }) => {
+ test('detects wordpressLikely by wp signatures', async ({ page }, {
+ testId
+ }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<head>
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>
</head>
<body>
<script src="/wp-content/themes/mytheme/script.js"></script>
@@ -321,7 +466,10 @@ test.describe('v1 verifier (WordPress detection)', () => {
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.wordpressPlugin).toBe(false)
expect(result.data.wordpressLikely).toBe(true)
@@ -334,33 +482,52 @@ test.describe('v1 verifier (GTM detection)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
- <head>
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>
- <!-- Google Tag Manager -->
- <script>
- (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
- new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
- j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
- 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
- })(window,document,'script','dataLayer','XXXX');
- </script>
- <!-- End Google Tag Manager -->
- </head>
- <body>Hello</body>
+ <head>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ <!-- Google Tag Manager -->
+ <script>
+ ;(function (w, d, s, l, i) {
+ w[l] = w[l] || []
+ w[l].push({
+ 'gtm.start': new Date().getTime(),
+ event: 'gtm.js'
+ })
+ var f = d.getElementsByTagName(s)[0],
+ j = d.createElement(s),
+ dl = l != 'dataLayer' ? '&l=' + l : ''
+ j.async = true
+ j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl
+ f.parentNode.insertBefore(j, f)
+ })(window, document, 'script', 'dataLayer', 'XXXX')
+ </script>
+ <!-- End Google Tag Manager -->
+ </head>
+ <body>
+ Hello
+ </body>
</html>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.gtmLikely).toBe(true)
})
})
test.describe('v1 verifier (cookieBanner detection)', () => {
- test('detects a dynamically loaded cookiebot', async ({ page }, { testId }) => {
+ test('detects a dynamically loaded cookiebot', async ({ page }, {
+ testId
+ }) => {
// While in real world the plausible script would be prevented
// from loading when cookiebot is present, to speed up the test
// we let it load, but mock a general network error. That is to
@@ -374,10 +541,14 @@ test.describe('v1 verifier (cookieBanner detection)', () => {
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>
</head>
<body>
<script>
@@ -385,51 +556,73 @@ test.describe('v1 verifier (cookieBanner detection)', () => {
const banner = document.createElement('div')
banner.id = 'CybotCookiebotDialog'
document.body.appendChild(banner)
- }, 500);
+ }, 500)
</script>
</body>
</html>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.cookieBannerLikely).toBe(true)
})
})
test.describe('v1 verifier (manualScriptExtension detection)', () => {
- test('manualScriptExtension is true when any snippet src has "manual." in it', async ({ page }, { testId }) => {
+ test('manualScriptExtension is true when any snippet src has "manual." in it', async ({
+ page
+ }, { testId }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.hash.js"></script>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.hash.js"
+ ></script>
</head>
<body>
- <script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.manual.js"></script>
+ <script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.manual.js"
+ ></script>
</body>
</html>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.manualScriptExtension).toBe(true)
})
})
test.describe('v1 verifier (unknownAttributes detection)', () => {
- test('unknownAttributes is false when all attrs are known', async ({ page }, { testId }) => {
+ test('unknownAttributes is false when all attrs are known', async ({ page }, {
+ testId
+ }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
<script
@@ -440,33 +633,46 @@ test.describe('v1 verifier (unknownAttributes detection)', () => {
data-include="some"
data-exclude="some"
data-domain="${SOME_DOMAIN}"
- src="/tracker/js/plausible.manual.js">
- </script>
+ src="/tracker/js/plausible.manual.js"
+ ></script>
</head>
</html>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.unknownAttributes).toBe(false)
})
- test('unknownAttributes is true when any unknown attributes are present', async ({ page }, { testId }) => {
+ test('unknownAttributes is true when any unknown attributes are present', async ({
+ page
+ }, { testId }) => {
await mockEventResponseSuccess(page)
const { url } = await initializePageDynamically(page, {
testId,
- response: `
+ response: /* HTML */ `
<html>
<head>
- <script async weird="one" data-domain="${SOME_DOMAIN}" src="/tracker/js/script.js"></script>
+ <script
+ async
+ weird="one"
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/script.js"
+ ></script>
</head>
</html>
`
})
- const result = await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ const result = await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN
+ })
expect(result.data.unknownAttributes).toBe(true)
})
@@ -477,31 +683,51 @@ test.describe('v1 verifier (logging)', () => {
await mockEventResponseSuccess(page)
let logs = []
- page.context().on('console', msg => msg.type() === 'log' && logs.push(msg.text()))
+ page
+ .context()
+ .on('console', (msg) => msg.type() === 'log' && logs.push(msg.text()))
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN, debug: true})
+ await verifyV1(page, {
+ url: url,
+ expectedDataDomain: SOME_DOMAIN,
+ debug: true
+ })
- expect(logs.find(str => str.includes('Starting snippet detection'))).toContain('[Plausible Verification] Starting snippet detection')
- expect(logs.find(str => str.includes('Checking for Plausible function'))).toContain('[Plausible Verification] Checking for Plausible function')
+ expect(
+ logs.find((str) => str.includes('Starting snippet detection'))
+ ).toContain('[Plausible Verification] Starting snippet detection')
+ expect(
+ logs.find((str) => str.includes('Checking for Plausible function'))
+ ).toContain('[Plausible Verification] Checking for Plausible function')
})
test('does not log by default', async ({ page }, { testId }) => {
await mockEventResponseSuccess(page)
let logs = []
- page.context().on('console', msg => msg.type() === 'log' && logs.push(msg.text()))
+ page
+ .context()
+ .on('console', (msg) => msg.type() === 'log' && logs.push(msg.text()))
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script async data-domain="${SOME_DOMAIN}" src="/tracker/js/plausible.local.js"></script>`
+ scriptConfig: /* HTML */ `<script
+ async
+ data-domain="${SOME_DOMAIN}"
+ src="/tracker/js/plausible.local.js"
+ ></script>`
})
- await verifyV1(page, {url: url, expectedDataDomain: SOME_DOMAIN})
+ await verifyV1(page, { url: url, expectedDataDomain: SOME_DOMAIN })
expect(logs.length).toBe(0)
})
diff --git a/tracker/test/installation_support/verifier-v2.spec.ts b/tracker/test/installation_support/verifier-v2.spec.ts
index 66736d74fc..a5812adf7e 100644
--- a/tracker/test/installation_support/verifier-v2.spec.ts
+++ b/tracker/test/installation_support/verifier-v2.spec.ts
@@ -592,13 +592,18 @@ test.describe('installed plausible esm variant', () => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; window.init = init; window.track = track; init(${JSON.stringify(
- {
- domain: 'example.com',
- endpoint: `https://plausible.io/api/event`,
- captureOnLocalhost: true
- }
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ init(
+ ${JSON.stringify({
+ domain: 'example.com',
+ endpoint: `https://plausible.io/api/event`,
+ captureOnLocalhost: true
+ })}
+ )
+ </script>`,
bodyContent: ''
})
@@ -652,13 +657,18 @@ test.describe('installed plausible esm variant', () => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; window.init = init; window.track = track; init(${JSON.stringify(
- {
- domain: 'example.com',
- endpoint: `/events`,
- captureOnLocalhost: true
- }
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ init(
+ ${JSON.stringify({
+ domain: 'example.com',
+ endpoint: `/events`,
+ captureOnLocalhost: true
+ })}
+ )
+ </script>`,
bodyContent: ''
})
@@ -701,13 +711,18 @@ test.describe('installed plausible esm variant', () => {
}, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; window.init = init; window.track = track; init(${JSON.stringify(
- {
- domain: 'example.com',
- endpoint: `https://example.com/events`,
- captureOnLocalhost: true
- }
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ init(
+ ${JSON.stringify({
+ domain: 'example.com',
+ endpoint: `https://example.com/events`,
+ captureOnLocalhost: true
+ })}
+ )
+ </script>`,
bodyContent: ''
})
@@ -761,13 +776,18 @@ test.describe('installed plausible esm variant', () => {
}, { testId }) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; window.init = init; window.track = track; init(${JSON.stringify(
- {
- domain: 'example.com/foobar',
- endpoint: 'invalid:/plausible.io/api/event',
- captureOnLocalhost: true
- }
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ init(
+ ${JSON.stringify({
+ domain: 'example.com/foobar',
+ endpoint: 'invalid:/plausible.io/api/event',
+ captureOnLocalhost: true
+ })}
+ )
+ </script>`,
bodyContent: ''
})
diff --git a/tracker/test/legacy-custom-properties.spec.js b/tracker/test/legacy-custom-properties.spec.js
index 65db5ed6b8..9d5c4f18c8 100644
--- a/tracker/test/legacy-custom-properties.spec.js
+++ b/tracker/test/legacy-custom-properties.spec.js
@@ -1,7 +1,4 @@
-import {
- expectPlausibleInAction,
- isPageviewEvent
-} from './support/test-utils'
+import { expectPlausibleInAction, isPageviewEvent } from './support/test-utils'
import { test } from '@playwright/test'
test.describe('legacy custom properties support', () => {
@@ -24,9 +21,7 @@ test.describe('legacy custom properties support', () => {
await page.goto('/legacy-custom-properties.html')
await page.click('#custom-props-button')
},
- expectedRequests: [
- { n: 'Props event', p: { type: 'props' } }
- ],
+ expectedRequests: [{ n: 'Props event', p: { type: 'props' } }],
shouldIgnoreRequest: isPageviewEvent
})
})
@@ -37,9 +32,7 @@ test.describe('legacy custom properties support', () => {
await page.goto('/legacy-custom-properties.html')
await page.click('#custom-meta-button')
},
- expectedRequests: [
- { n: 'Meta event', m: '{"type":"meta"}' }
- ],
+ expectedRequests: [{ n: 'Meta event', m: '{"type":"meta"}' }],
shouldIgnoreRequest: isPageviewEvent
})
})
diff --git a/tracker/test/logging.spec.ts b/tracker/test/logging.spec.ts
index dcc89d4cf9..9696031772 100644
--- a/tracker/test/logging.spec.ts
+++ b/tracker/test/logging.spec.ts
@@ -1,8 +1,5 @@
import { initializePageDynamically } from './support/initialize-page-dynamically'
-import {
- expectPlausibleInAction,
- switchByMode,
-} from './support/test-utils'
+import { expectPlausibleInAction, switchByMode } from './support/test-utils'
import { expect, test } from '@playwright/test'
import { ScriptConfig } from './support/types'
import { LOCAL_SERVER_ADDR } from './support/server'
diff --git a/tracker/test/manual.spec.js b/tracker/test/manual.spec.js
index 7c2615b505..4e358c046e 100644
--- a/tracker/test/manual.spec.js
+++ b/tracker/test/manual.spec.js
@@ -3,45 +3,74 @@ import { test } from '@playwright/test'
import { LOCAL_SERVER_ADDR } from './support/server'
test.describe('manual extension', () => {
- test('can trigger custom events with and without a custom URL if pageview was sent with the default URL', async ({ page }) => {
+ test('can trigger custom events with and without a custom URL if pageview was sent with the default URL', async ({
+ page
+ }) => {
await page.goto('/manual.html')
await expectPlausibleInAction(page, {
action: () => page.click('#pageview-trigger'),
- expectedRequests: [{n: 'pageview', u: `${LOCAL_SERVER_ADDR}/manual.html`}]
+ expectedRequests: [
+ { n: 'pageview', u: `${LOCAL_SERVER_ADDR}/manual.html` }
+ ]
})
await expectPlausibleInAction(page, {
action: () => page.click('#custom-event-trigger'),
- expectedRequests: [{n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html`}]
+ expectedRequests: [
+ { n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html` }
+ ]
})
await expectPlausibleInAction(page, {
action: () => page.click('#custom-event-trigger-custom-url'),
- expectedRequests: [{n: 'CustomEvent', u: `https://example.com/custom/location`}]
+ expectedRequests: [
+ { n: 'CustomEvent', u: `https://example.com/custom/location` }
+ ]
})
})
- test('can trigger custom events with and without a custom URL if pageview was sent with a custom URL', async ({ page }) => {
+ test('can trigger custom events with and without a custom URL if pageview was sent with a custom URL', async ({
+ page
+ }) => {
await page.goto('/manual.html')
await expectPlausibleInAction(page, {
action: () => page.click('#pageview-trigger-custom-url'),
- expectedRequests: [{n: 'pageview', u: `https://example.com/custom/location`}]
+ expectedRequests: [
+ { n: 'pageview', u: `https://example.com/custom/location` }
+ ]
})
await expectPlausibleInAction(page, {
action: () => page.click('#custom-event-trigger'),
- expectedRequests: [{n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html`}]
+ expectedRequests: [
+ { n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html` }
+ ]
})
await expectPlausibleInAction(page, {
action: () => page.click('#custom-event-trigger-custom-url'),
- expectedRequests: [{n: 'CustomEvent', u: `https://example.com/custom/location`}]
+ expectedRequests: [
+ { n: 'CustomEvent', u: `https://example.com/custom/location` }
+ ]
})
})
- test('can trigger custom events with interactive: false', async ({ page }) => {
+ test('can trigger custom events with interactive: false', async ({
+ page
+ }) => {
await page.goto('/manual.html')
await expectPlausibleInAction(page, {
- action: () => page.evaluate(() => window.plausible('Non-Interactive Custom Event', { interactive: false })),
- expectedRequests: [{n: 'Non-Interactive Custom Event', u: `${LOCAL_SERVER_ADDR}/manual.html`, i: false}]
+ action: () =>
+ page.evaluate(() =>
+ window.plausible('Non-Interactive Custom Event', {
+ interactive: false
+ })
+ ),
+ expectedRequests: [
+ {
+ n: 'Non-Interactive Custom Event',
+ u: `${LOCAL_SERVER_ADDR}/manual.html`,
+ i: false
+ }
+ ]
})
})
})
diff --git a/tracker/test/outbound-links.spec.ts b/tracker/test/outbound-links.spec.ts
index b9f3166700..632bad9142 100644
--- a/tracker/test/outbound-links.spec.ts
+++ b/tracker/test/outbound-links.spec.ts
@@ -47,7 +47,7 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<a href="${outboundUrl}">➡️</a>`
+ bodyContent: /* HTML */ `<a href="${outboundUrl}">➡️</a>`
})
await expectPlausibleInAction(page, {
@@ -94,7 +94,7 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<a href="${outboundUrl}">➡️</a>`
+ bodyContent: /* HTML */ `<a href="${outboundUrl}">➡️</a>`
})
await expectPlausibleInAction(page, {
@@ -169,7 +169,7 @@ for (const mode of ['legacy', 'web'])
},
mode
),
- bodyContent: `<a href="${outboundUrl}"><h1>➡️</h1></a>`
+ bodyContent: /* HTML */ `<a href="${outboundUrl}"><h1>➡️</h1></a>`
})
await page.goto(url)
@@ -219,7 +219,7 @@ for (const mode of ['legacy', 'web'])
},
mode
),
- bodyContent: `<a href="${outboundUrl}">>➡️</a>`
+ bodyContent: /* HTML */ `<a href="${outboundUrl}">>➡️</a>`
})
await page.goto(url)
await page.click('a')
@@ -268,7 +268,7 @@ for (const mode of ['legacy', 'web'])
},
mode
),
- bodyContent: `
+ bodyContent: /* HTML */ `
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<a href="${outboundUrl}">
<circle cx="50" cy="50" r="50" />
@@ -359,7 +359,9 @@ test.describe('outbound links feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
- bodyContent: `<a ${linkAttributes} href="${outboundUrl}"><h1>➡️</h1></a>`
+ bodyContent: /* HTML */ `<a ${linkAttributes} href="${outboundUrl}"
+ ><h1>➡️</h1></a
+ >`
})
await page.goto(url)
@@ -402,7 +404,7 @@ test.describe('outbound links feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
- bodyContent: `<a href="${outboundUrl}">📥</a>`
+ bodyContent: /* HTML */ `<a href="${outboundUrl}">📥</a>`
})
await page.goto(url)
@@ -454,7 +456,7 @@ test.describe('outbound links feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
- bodyContent: `<a href="${outboundUrl}">➡️</a>`
+ bodyContent: /* HTML */ `<a href="${outboundUrl}">➡️</a>`
})
await page.goto(url)
const navigationPromise = page.waitForRequest(outboundUrl, {
@@ -495,7 +497,7 @@ test.describe('outbound links feature when using legacy .compat extension', () =
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
- bodyContent: `
+ bodyContent: /* HTML */ `
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<a href="${outboundUrl}">
<circle cx="50" cy="50" r="50" />
diff --git a/tracker/test/pageview.spec.ts b/tracker/test/pageview.spec.ts
index b3cb837a9b..c7a4d63b5b 100644
--- a/tracker/test/pageview.spec.ts
+++ b/tracker/test/pageview.spec.ts
@@ -76,9 +76,19 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `
- <a id="alfa" onclick="window.plausible('pageview', { u: '/:masked/alfa' })" href="#">A</a>
- <a id="beta" onclick="window.plausible('pageview', { url: '/:masked/beta' })" href="#">B</a>
+ bodyContent: /* HTML */ `
+ <a
+ id="alfa"
+ onclick="window.plausible('pageview', { u: '/:masked/alfa' })"
+ href="#"
+ >A</a
+ >
+ <a
+ id="beta"
+ onclick="window.plausible('pageview', { url: '/:masked/beta' })"
+ href="#"
+ >B</a
+ >
`
})
@@ -132,7 +142,7 @@ for (const mode of ['legacy', 'web', 'esm']) {
d: DEFAULT_CONFIG.domain,
u: `${LOCAL_SERVER_ADDR}${url}`,
v: tracker_script_version,
- h: e.toBeUndefined(),
+ h: e.toBeUndefined()
}
],
shouldIgnoreRequest: [isEngagementEvent]
diff --git a/tracker/test/plausible-npm-init.spec.ts b/tracker/test/plausible-npm-init.spec.ts
index 832835150e..9848863f76 100644
--- a/tracker/test/plausible-npm-init.spec.ts
+++ b/tracker/test/plausible-npm-init.spec.ts
@@ -31,7 +31,11 @@ test('if `init` is called without domain, it throws', async ({ page }, {
}) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; window.init = init; window.track = track;</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ </script>`,
bodyContent: 'body'
})
await page.goto(url)
@@ -46,7 +50,11 @@ test('if `init` is called with no configuration, it throws', async ({ page }, {
}) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; window.init = init; window.track = track;</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ </script>`,
bodyContent: 'body'
})
await page.goto(url)
@@ -60,13 +68,15 @@ test('if `track` is called before `init`, it throws', async ({ page }, {
}) => {
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; window.init = init; window.track = track;</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ window.track = track
+ </script>`,
bodyContent: 'body'
})
await page.goto(url)
- await expect(
- page.evaluate(() => window.track('purchase'))
- ).rejects.toThrow(
+ await expect(page.evaluate(() => window.track('purchase'))).rejects.toThrow(
'plausible.track() can only be called after plausible.init()'
)
})
@@ -77,9 +87,11 @@ test('if `init` is called twice, it throws, but tracking still works', async ({
const config = { ...DEFAULT_CONFIG }
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; window.init = init; init(${JSON.stringify(
- config
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ window.init = init
+ init(${JSON.stringify(config)})
+ </script>`,
bodyContent: 'body'
})
@@ -109,9 +121,10 @@ test('`bindToWindow` is true by default, and plausible is attached to window', a
const config = { ...DEFAULT_CONFIG }
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; init(${JSON.stringify(
- config
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ init(${JSON.stringify(config)})
+ </script>`,
bodyContent: 'body'
})
@@ -144,9 +157,10 @@ test('if `bindToWindow` is false, plausible is not attached to window', async ({
const config = { ...DEFAULT_CONFIG, bindToWindow: false }
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; init(${JSON.stringify(
- config
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ init(${JSON.stringify(config)})
+ </script>`,
bodyContent: 'body'
})
@@ -159,13 +173,9 @@ test('if `bindToWindow` is false, plausible is not attached to window', async ({
})
await expect(
- page.waitForFunction(
- () => window.plausible !== undefined,
- undefined,
- {
- timeout: 1000
- }
- )
+ page.waitForFunction(() => window.plausible !== undefined, undefined, {
+ timeout: 1000
+ })
).rejects.toThrow('page.waitForFunction: Timeout 1000ms exceeded.')
})
@@ -175,9 +185,10 @@ test('allows overriding `endpoint` with a custom URL via `init`', async ({
const config = { ...DEFAULT_CONFIG, endpoint: 'http://example.com/event' }
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `<script type="module">import { init, track } from "/tracker/js/npm_package/plausible.js"; init(${JSON.stringify(
- config
- )})</script>`,
+ scriptConfig: /* HTML */ `<script type="module">
+ import { init, track } from '/tracker/js/npm_package/plausible.js'
+ init(${JSON.stringify(config)})
+ </script>`,
bodyContent: 'body'
})
await expectPlausibleInAction(page, {
diff --git a/tracker/test/plausible-web-init.spec.ts b/tracker/test/plausible-web-init.spec.ts
index e95c9b4cfb..adc745e8af 100644
--- a/tracker/test/plausible-web-init.spec.ts
+++ b/tracker/test/plausible-web-init.spec.ts
@@ -54,7 +54,9 @@ test('handles double-initialization of the script with a console.warn', async ({
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig: config,
- bodyContent: `<button onclick="window.plausible('Purchase')">Purchase</button>`
+ bodyContent: /* HTML */ `<button onclick="window.plausible('Purchase')">
+ Purchase
+ </button>`
})
const messages: [string, string][] = []
page.on('console', (message) => {
@@ -90,14 +92,21 @@ test('handles double-initialization of the script with a console.warn', async ({
})
})
-test('if there are two snippets on the page, one wins, no warning is emitted', async ({ page }, {
- testId
-}) => {
+test('if there are two snippets on the page, one wins, no warning is emitted', async ({
+ page
+}, { testId }) => {
const config = { ...DEFAULT_CONFIG }
- const snippetAlfa = getConfiguredPlausibleWebSnippet({...config, customProperties: { alfa: true }})
- const initCallAlfa = 'plausible.init({"captureOnLocalhost":true,"customProperties":{"alfa":true}})'
- expect(snippetAlfa).toEqual(expect.stringContaining(initCallAlfa))
- const snippetBeta = getConfiguredPlausibleWebSnippet({...config, customProperties: { beta: true }})
+ const snippetAlfa = getConfiguredPlausibleWebSnippet({
+ ...config,
+ customProperties: { alfa: true }
+ })
+ const initCallAlfa =
+ 'plausible.init({"captureOnLocalhost":true,"customProperties":{"alfa":true}})'
+ expect(snippetAlfa).toEqual(expect.stringContaining(initCallAlfa))
+ const snippetBeta = getConfiguredPlausibleWebSnippet({
+ ...config,
+ customProperties: { beta: true }
+ })
const initCallBeta = `plausible.init({"captureOnLocalhost":true,"customProperties":{"beta":true}})`
expect(snippetBeta).toEqual(expect.stringContaining(initCallBeta))
@@ -108,18 +117,22 @@ test('if there are two snippets on the page, one wins, no warning is emitted', a
const { url } = await initializePageDynamically(page, {
testId,
- scriptConfig: `${snippetAlfa}${snippetBeta}`,
+ scriptConfig: /* HTML */ `${snippetAlfa}${snippetBeta}`,
bodyContent: ''
})
await expectPlausibleInAction(page, {
action: () => page.goto(url),
expectedRequests: [
- { n: 'pageview', d: config.domain, u: `${LOCAL_SERVER_ADDR}${url}`, p: { beta: true } },
+ {
+ n: 'pageview',
+ d: config.domain,
+ u: `${LOCAL_SERVER_ADDR}${url}`,
+ p: { beta: true }
+ }
],
shouldIgnoreRequest: isEngagementEvent
})
expect(messages).toEqual([])
-
})
test('if domain is provided in `init`, it is ignored', async ({ page }, {
@@ -129,7 +142,7 @@ test('if domain is provided in `init`, it is ignored', async ({ page }, {
const scriptConfig = getConfiguredPlausibleWebSnippet(config)
const originalInitCall = 'plausible.init({"captureOnLocalhost":true})'
// verify that the original snippet is what we expect it to be
- expect(scriptConfig).toEqual(expect.stringContaining(originalInitCall))
+ expect(scriptConfig).toEqual(expect.stringContaining(originalInitCall))
const initCallWithDomainOverride = `plausible.init({"captureOnLocalhost":true,"domain":"sub.${config.domain}"})`
const updatedScriptConfig = scriptConfig.replace(
originalInitCall,
diff --git a/tracker/test/revenue.spec.js b/tracker/test/revenue.spec.js
index cb98a082b6..f17a888882 100644
--- a/tracker/test/revenue.spec.js
+++ b/tracker/test/revenue.spec.js
@@ -7,16 +7,22 @@ test.describe('with revenue script extension', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#manual-purchase'),
- expectedRequests: [{n: "Purchase", $: {amount: 15.99, currency: "USD"}}]
+ expectedRequests: [
+ { n: 'Purchase', $: { amount: 15.99, currency: 'USD' } }
+ ]
})
})
- test('sends revenue currency and amount with tagged class name', async ({ page }) => {
+ test('sends revenue currency and amount with tagged class name', async ({
+ page
+ }) => {
await page.goto('/revenue.html')
await expectPlausibleInAction(page, {
action: () => page.click('#tagged-purchase'),
- expectedRequests: [{n: "Purchase", $: {amount: "13.32", currency: "EUR"}}]
+ expectedRequests: [
+ { n: 'Purchase', $: { amount: '13.32', currency: 'EUR' } }
+ ]
})
})
})
diff --git a/tracker/test/scroll-depth.spec.js b/tracker/test/scroll-depth.spec.js
index 1b648a28d2..daf9ed58c2 100644
--- a/tracker/test/scroll-depth.spec.js
+++ b/tracker/test/scroll-depth.spec.js
@@ -1,12 +1,18 @@
-import { expectPlausibleInAction, hideCurrentTab, hideAndShowCurrentTab } from './support/test-utils'
+import {
+ expectPlausibleInAction,
+ hideCurrentTab,
+ hideAndShowCurrentTab
+} from './support/test-utils'
import { test, expect } from '@playwright/test'
import { LOCAL_SERVER_ADDR } from './support/server'
test.describe('scroll depth (engagement events)', () => {
- test('sends scroll_depth in the pageleave payload when navigating to the next page', async ({ page }) => {
+ test('sends scroll_depth in the pageleave payload when navigating to the next page', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/scroll-depth.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.evaluate(() => window.scrollBy(0, 300))
@@ -14,37 +20,52 @@ test.describe('scroll depth (engagement events)', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20}]
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20 }
+ ]
})
})
test('sends scroll depth on hash navigation', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/scroll-depth-hash.html'),
- expectedRequests: [{n: 'pageview'}]
+ expectedRequests: [{ n: 'pageview' }]
})
await expectPlausibleInAction(page, {
action: () => page.click('#about-link'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html`, sd: 100},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`}
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html`,
+ sd: 100
+ },
+ {
+ n: 'pageview',
+ u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`
+ }
]
})
await expectPlausibleInAction(page, {
action: () => page.click('#home-link'),
expectedRequests: [
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`, sd: 34},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#home`}
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`,
+ sd: 34
+ },
+ { n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#home` }
]
})
})
- test('document height gets reevaluated after window load', async ({ page }) => {
+ test('document height gets reevaluated after window load', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/scroll-depth-slow-window-load.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
// Wait for the image to be loaded
@@ -54,30 +75,41 @@ test.describe('scroll depth (engagement events)', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{
- n: 'engagement',
- u: `${LOCAL_SERVER_ADDR}/scroll-depth-slow-window-load.html`, sd: 24
- }]
+ expectedRequests: [
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/scroll-depth-slow-window-load.html`,
+ sd: 24
+ }
+ ]
})
})
- test('dynamically loaded content affects documentHeight', async ({ page }) => {
+ test('dynamically loaded content affects documentHeight', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/scroll-depth-dynamic-content-load.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
// The link appears dynamically after 500ms.
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth-dynamic-content-load.html`, sd: 14}]
+ expectedRequests: [
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/scroll-depth-dynamic-content-load.html`,
+ sd: 14
+ }
+ ]
})
})
test('document height gets reevaluated on scroll', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/scroll-depth-content-onscroll.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
// During the first 3 seconds, the script periodically updates document height
@@ -95,14 +127,20 @@ test.describe('scroll depth (engagement events)', () => {
await expectPlausibleInAction(page, {
action: () => page.click('#navigate-away'),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth-content-onscroll.html`, sd: 80}]
+ expectedRequests: [
+ {
+ n: 'engagement',
+ u: `${LOCAL_SERVER_ADDR}/scroll-depth-content-onscroll.html`,
+ sd: 80
+ }
+ ]
})
})
test('sends scroll depth when minimizing the tab', async ({ page }) => {
await expectPlausibleInAction(page, {
action: () => page.goto('/scroll-depth.html'),
- expectedRequests: [{n: 'pageview'}],
+ expectedRequests: [{ n: 'pageview' }]
})
await page.evaluate(() => window.scrollBy(0, 300))
@@ -110,11 +148,16 @@ test.describe('scroll depth (engagement events)', () => {
await expectPlausibleInAction(page, {
action: () => hideCurrentTab(page),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20}],
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20 }
+ ]
})
})
- test('re-sends engagement events only when user has scrolled in-between', async ({ page, browserName }) => {
+ test('re-sends engagement events only when user has scrolled in-between', async ({
+ page,
+ browserName
+ }) => {
test.skip(browserName === 'webkit', 'flaky')
await expectPlausibleInAction(page, {
@@ -123,36 +166,39 @@ test.describe('scroll depth (engagement events)', () => {
await hideAndShowCurrentTab(page)
},
expectedRequests: [
- {n: 'pageview'},
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 14}
- ],
+ { n: 'pageview' },
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 14 }
+ ]
})
await expectPlausibleInAction(page, {
action: () => hideAndShowCurrentTab(page),
expectedRequests: [],
- refutedRequests: [{n: 'engagement'}]
+ refutedRequests: [{ n: 'engagement' }]
})
await page.evaluate(() => window.scrollBy(0, 300))
await expectPlausibleInAction(page, {
action: () => hideCurrentTab(page),
- expectedRequests: [{n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20}],
+ expectedRequests: [
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20 }
+ ]
})
})
-
- test('gets correct scroll depth when script has no async', async ({ page }) => {
+ test('gets correct scroll depth when script has no async', async ({
+ page
+ }) => {
await expectPlausibleInAction(page, {
action: async () => {
await page.goto('/no-async.html')
await hideAndShowCurrentTab(page)
},
expectedRequests: [
- {n: 'pageview'},
- {n: 'engagement', u: `${LOCAL_SERVER_ADDR}/no-async.html`, sd: 100}
- ],
+ { n: 'pageview' },
+ { n: 'engagement', u: `${LOCAL_SERVER_ADDR}/no-async.html`, sd: 100 }
+ ]
})
await page.waitForTimeout(1000)
diff --git a/tracker/test/support/html-fixtures.ts b/tracker/test/support/html-fixtures.ts
index 1694d1f48d..8ea6f228c0 100644
--- a/tracker/test/support/html-fixtures.ts
+++ b/tracker/test/support/html-fixtures.ts
@@ -3,4 +3,5 @@
* Overriding onsubmit with a custom handler is common practice in web development for a variety of reasons (mostly UX),
* so this stub can be used in tests to simulate such behavior.
*/
-export const customSubmitHandlerStub = "event.preventDefault(); console.log('Submitted')"
+export const customSubmitHandlerStub =
+ '"event.preventDefault(); console.log(\'Submitted\')"'
diff --git a/tracker/test/support/installation-support-playwright-wrappers.ts b/tracker/test/support/installation-support-playwright-wrappers.ts
index 788eacdc2d..2350ebf1aa 100644
--- a/tracker/test/support/installation-support-playwright-wrappers.ts
+++ b/tracker/test/support/installation-support-playwright-wrappers.ts
@@ -14,8 +14,13 @@ const DETECTOR_JS_VARIANT = variantsFile.manualVariants.find(
)
export async function executeVerifyV2(
- page: Page,
- { responseHeaders, maxAttempts, timeoutBetweenAttemptsMs, ...functionContext }: VerifyV2Args & { maxAttempts: number, timeoutBetweenAttemptsMs: number }
+ page: Page,
+ {
+ responseHeaders,
+ maxAttempts,
+ timeoutBetweenAttemptsMs,
+ ...functionContext
+ }: VerifyV2Args & { maxAttempts: number; timeoutBetweenAttemptsMs: number }
): Promise<VerifyV2Result> {
const verifierCode = (await compileFile(VERIFIER_V2_JS_VARIANT, {
returnCode: true
@@ -26,34 +31,38 @@ export async function executeVerifyV2(
await page.evaluate(verifierCode) // injects window.verifyPlausibleInstallation
return await page.evaluate(
// @ts-expect-error - window.verifyPlausibleInstallation has been injected
- (c) => {return window.verifyPlausibleInstallation(c)},
- {...functionContext, responseHeaders}
- );
+ (c) => {
+ return window.verifyPlausibleInstallation(c)
+ },
+ { ...functionContext, responseHeaders }
+ )
}
- let lastError;
+ let lastError
for (let attempts = 1; attempts <= maxAttempts; attempts++) {
try {
- const output = await verify();
+ const output = await verify()
return {
data: {
...output.data,
attempts
- },
- };
+ }
+ }
} catch (error) {
- lastError = error;
+ lastError = error
if (
- typeof error?.message === "string" &&
- error.message.toLowerCase().includes("execution context")
+ typeof error?.message === 'string' &&
+ error.message.toLowerCase().includes('execution context')
) {
- await new Promise((resolve) => setTimeout(resolve, timeoutBetweenAttemptsMs));
- continue;
+ await new Promise((resolve) =>
+ setTimeout(resolve, timeoutBetweenAttemptsMs)
+ )
+ continue
}
throw error
}
}
- throw lastError;
+ throw lastError
} catch (error) {
return {
data: {
@@ -80,10 +89,7 @@ export async function verifyV1(page, context) {
return await page.evaluate(
async ({ expectedDataDomain, debug }) => {
// @ts-expect-error - window.verifyPlausibleInstallation has been injected
- return await window.verifyPlausibleInstallation(
- expectedDataDomain,
- debug
- )
+ return await window.verifyPlausibleInstallation(expectedDataDomain, debug)
},
{ expectedDataDomain, debug }
)
diff --git a/tracker/test/support/server.js b/tracker/test/support/server.js
index 8894b0605c..39df1e4a86 100644
--- a/tracker/test/support/server.js
+++ b/tracker/test/support/server.js
@@ -5,9 +5,9 @@ import { compileFile } from '../../compiler/index.js'
import variantsFile from '../../compiler/variants.json' with { type: 'json' }
const __dirname = path.dirname(fileURLToPath(import.meta.url))
-const isMainModule = fileURLToPath(import.meta.url) === process.argv[1];
+const isMainModule = fileURLToPath(import.meta.url) === process.argv[1]
-const app = express();
+const app = express()
const LOCAL_SERVER_PORT = 3000
const FIXTURES_PATH = path.join(__dirname, '/../fixtures')
const VARIANTS = variantsFile.legacyVariants.concat(variantsFile.manualVariants)
@@ -15,13 +15,16 @@ const VARIANTS = variantsFile.legacyVariants.concat(variantsFile.manualVariants)
export const LOCAL_SERVER_ADDR = `http://localhost:${LOCAL_SERVER_PORT}`
export function runLocalFileServer() {
- app.use(express.static(FIXTURES_PATH));
+ app.use(express.static(FIXTURES_PATH))
app.get('/tracker/js/*', async (req, res) => {
const name = req.params[0]
const variant = VARIANTS.find((variant) => variant.name === name)
if (!variant) {
- res.type('application/javascript').status(404).send({error: new Error(`Variant not found with name ${name}`)})
+ res
+ .type('application/javascript')
+ .status(404)
+ .send({ error: new Error(`Variant not found with name ${name}`) })
} else {
let code = await compileFile(variant, { returnCode: true })
@@ -30,19 +33,19 @@ export function runLocalFileServer() {
}
res.type('application/javascript').send(code)
- }
- });
+ }
+ })
// A test utility - serve an image with an artificial delay
app.get('/img/slow-image', (_req, res) => {
setTimeout(() => {
- res.sendFile(path.join(FIXTURES_PATH, '/img/black3x3000.png'));
- }, 100);
- });
+ res.sendFile(path.join(FIXTURES_PATH, '/img/black3x3000.png'))
+ }, 100)
+ })
app.listen(LOCAL_SERVER_PORT, function () {
console.log(`Local server listening on ${LOCAL_SERVER_ADDR}`)
- });
+ })
}
if (isMainModule) {
diff --git a/tracker/test/support/test-utils.js b/tracker/test/support/test-utils.js
index c314bc965a..d2b1cd7b68 100644
--- a/tracker/test/support/test-utils.js
+++ b/tracker/test/support/test-utils.js
@@ -1,6 +1,6 @@
-import { expect } from "@playwright/test"
+import { expect } from '@playwright/test'
import packageJson from '../../package.json' with { type: 'json' }
-import { mockManyRequests } from "./mock-many-requests"
+import { mockManyRequests } from './mock-many-requests'
export const tracker_script_version = packageJson.tracker_script_version
@@ -33,19 +33,26 @@ export const tracker_script_version = packageJson.tracker_script_version
* API by the given number of milliseconds.
* @param {number} [args.mockRequestTimeout] - How long to wait for the requests to be made
*/
-export const expectPlausibleInAction = async function (page, {
- action,
- expectedRequests = [],
- refutedRequests = [],
- pathToMock = '/api/event',
- awaitedRequestCount,
- expectedRequestCount,
- responseDelay,
- shouldIgnoreRequest,
- mockRequestTimeout = 3000
-}) {
- const requestsToExpect = expectedRequestCount ? expectedRequestCount : expectedRequests.length
- const requestsToAwait = awaitedRequestCount ? awaitedRequestCount : requestsToExpect + refutedRequests.length
+export const expectPlausibleInAction = async function (
+ page,
+ {
+ action,
+ expectedRequests = [],
+ refutedRequests = [],
+ pathToMock = '/api/event',
+ awaitedRequestCount,
+ expectedRequestCount,
+ responseDelay,
+ shouldIgnoreRequest,
+ mockRequestTimeout = 3000
+ }
+) {
+ const requestsToExpect = expectedRequestCount
+ ? expectedRequestCount
+ : expectedRequests.length
+ const requestsToAwait = awaitedRequestCount
+ ? awaitedRequestCount
+ : requestsToExpect + refutedRequests.length
const { getRequestList } = await mockManyRequests({
page,
@@ -66,7 +73,9 @@ export const expectPlausibleInAction = async function (page, {
return includesSubset(requestBody, bodySubset)
})
- if (!wasFound) {expectedButNotFoundBodySubsets.push(bodySubset)}
+ if (!wasFound) {
+ expectedButNotFoundBodySubsets.push(bodySubset)
+ }
})
const refutedButFoundRequestBodies = []
@@ -76,63 +85,79 @@ export const expectPlausibleInAction = async function (page, {
return includesSubset(requestBody, bodySubset)
})
- if (found) {refutedButFoundRequestBodies.push(found)}
+ if (found) {
+ refutedButFoundRequestBodies.push(found)
+ }
})
const expectedBodySubsetsErrorMessage = `The following body subsets were not found from the requests that were made:\n\n${JSON.stringify(expectedButNotFoundBodySubsets, null, 4)}\n\nReceived requests with the following bodies:\n\n${JSON.stringify(requestBodies, null, 4)}`
- expect(expectedButNotFoundBodySubsets, expectedBodySubsetsErrorMessage).toHaveLength(0)
+ expect(
+ expectedButNotFoundBodySubsets,
+ expectedBodySubsetsErrorMessage
+ ).toHaveLength(0)
const refutedBodySubsetsErrorMessage = `The following requests were made, but were not expected:\n\n${JSON.stringify(refutedButFoundRequestBodies, null, 4)}`
- expect(refutedButFoundRequestBodies, refutedBodySubsetsErrorMessage).toHaveLength(0)
+ expect(
+ refutedButFoundRequestBodies,
+ refutedBodySubsetsErrorMessage
+ ).toHaveLength(0)
const unexpectedRequestBodiesErrorMessage = `Expected ${requestsToExpect} requests, but received ${requestBodies.length}:\n\n${JSON.stringify(requestBodies, null, 4)}`
- expect(requestBodies.length, unexpectedRequestBodiesErrorMessage).toBe(requestsToExpect)
+ expect(requestBodies.length, unexpectedRequestBodiesErrorMessage).toBe(
+ requestsToExpect
+ )
return requestBodies
}
-export const isPageviewEvent = function(requestPostData) {
+export const isPageviewEvent = function (requestPostData) {
return requestPostData.n === 'pageview'
}
-export const isEngagementEvent = function(requestPostData) {
+export const isEngagementEvent = function (requestPostData) {
return requestPostData.n === 'engagement'
}
async function toggleTabVisibility(page, hide) {
await page.evaluate((hide) => {
- Object.defineProperty(document, 'visibilityState', { value: hide ? 'hidden' : 'visible', writable: true })
+ Object.defineProperty(document, 'visibilityState', {
+ value: hide ? 'hidden' : 'visible',
+ writable: true
+ })
Object.defineProperty(document, 'hidden', { value: hide, writable: true })
document.dispatchEvent(new Event('visibilitychange'))
}, hide)
}
-export const hideCurrentTab = async function(page) {
+export const hideCurrentTab = async function (page) {
return toggleTabVisibility(page, true)
}
-export const showCurrentTab = async function(page) {
+export const showCurrentTab = async function (page) {
return toggleTabVisibility(page, false)
}
async function setFocus(page, focus) {
await page.evaluate((focus) => {
- Object.defineProperty(document, 'hasFocus', { value: () => focus, writable: true })
+ Object.defineProperty(document, 'hasFocus', {
+ value: () => focus,
+ writable: true
+ })
const eventName = focus ? 'focus' : 'blur'
window.dispatchEvent(new Event(eventName))
}, focus)
}
-export const focus = async function(page) {
+export const focus = async function (page) {
return setFocus(page, true)
}
-export const blur = async function(page) {
+export const blur = async function (page) {
return setFocus(page, false)
}
-export const hideAndShowCurrentTab = async function(page, options = {}) {
+export const hideAndShowCurrentTab = async function (page, options = {}) {
await hideCurrentTab(page)
if (options.delay > 0) {
await delay(options.delay)
@@ -140,7 +165,7 @@ export const hideAndShowCurrentTab = async function(page, options = {}) {
await showCurrentTab(page)
}
-export const blurAndFocusPage = async function(page, options = {}) {
+export const blurAndFocusPage = async function (page, options = {}) {
await blur(page)
if (options.delay > 0) {
await delay(options.delay)
@@ -163,7 +188,10 @@ export const e = {
function includesSubset(body, subset) {
return Object.keys(subset).every((key) => {
if (typeof subset[key] === 'object' && !subset[key].__expectation__) {
- return typeof body[key] === 'object' && areFlatObjectsEqual(body[key], subset[key])
+ return (
+ typeof body[key] === 'object' &&
+ areFlatObjectsEqual(body[key], subset[key])
+ )
} else {
return checkEqual(body[key], subset[key])
}
@@ -176,9 +204,9 @@ function areFlatObjectsEqual(obj1, obj2) {
const keys1 = Object.keys(obj1)
const keys2 = Object.keys(obj2)
- if (keys1.length !== keys2.length) return false;
+ if (keys1.length !== keys2.length) return false
- return keys1.every(key => checkEqual(obj2[key], obj1[key]))
+ return keys1.every((key) => checkEqual(obj2[key], obj1[key]))
}
function checkEqual(a, b) {
@@ -189,14 +217,14 @@ function checkEqual(a, b) {
}
export function delay(ms) {
- return new Promise(resolve => setTimeout(resolve, ms))
+ return new Promise((resolve) => setTimeout(resolve, ms))
}
export function switchByMode(cases, mode) {
switch (mode) {
case 'web':
return cases.web
- case 'esm':
+ case 'esm':
return cases.esm
case 'legacy':
return cases.legacy
@@ -208,10 +236,10 @@ export function switchByMode(cases, mode) {
/**
* This function ensures that the tracker script has attached the event listener before test is run.
* Note that this race condition happens in the real world as well:
- * Events from features like form submissions, file downloads, outbound links, tagged events
+ * Events from features like form submissions, file downloads, outbound links, tagged events
* that work with event handlers registered on the document
* will not be tracked if the event happens before the tracker script has attached the event listener.
*/
export function ensurePlausibleInitialized(page) {
- return page.waitForFunction(() =>(window.plausible?.l === true))
+ return page.waitForFunction(() => window.plausible?.l === true)
}
diff --git a/tracker/test/tagged-events.spec.ts b/tracker/test/tagged-events.spec.ts
index e807616a38..ae60605568 100644
--- a/tracker/test/tagged-events.spec.ts
+++ b/tracker/test/tagged-events.spec.ts
@@ -47,7 +47,11 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<a class="plausible-event-name=Purchase plausible-event-discounted=true plausible-revenue-currency=EUR plausible-revenue-amount=13.32" href="https://example.com/target">Purchase</a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-name=Purchase plausible-event-discounted=true plausible-revenue-currency=EUR plausible-revenue-amount=13.32"
+ href="https://example.com/target"
+ >Purchase</a
+ >`
})
await expectPlausibleInAction(page, {
action: async () => {
@@ -82,9 +86,11 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `
- <a class="plausible-event-name--Payment+Complete should ignore-this plausible-event-amount--100 plausible-event-method--Credit+Card" href="https://example.com/payment?secret=foo">
- <h1>✅</h1>
+ bodyContent: /* HTML */ ` <a
+ class="plausible-event-name--Payment+Complete should ignore-this plausible-event-amount--100 plausible-event-method--Credit+Card"
+ href="https://example.com/payment?secret=foo"
+ >
+ <h1>✅</h1>
</a>`
})
await page.goto(url)
@@ -125,8 +131,12 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<div class="plausible-event-name=Reset+Password plausible-event-foo=bar">
- <a href="https://example.com/reset?verification=123">Reset password</a>
+ bodyContent: /* HTML */ `<div
+ class="plausible-event-name=Reset+Password plausible-event-foo=bar"
+ >
+ <a href="https://example.com/reset?verification=123"
+ >Reset password</a
+ >
</div>`
})
await page.goto(url)
@@ -159,8 +169,11 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `
- <form class="plausible-event-name=Signup plausible-event-type=Newsletter" action="https://example.com/register" method="post">
+ bodyContent: /* HTML */ ` <form
+ class="plausible-event-name=Signup plausible-event-type=Newsletter"
+ action="https://example.com/register"
+ method="post"
+ >
<h2>Newsletter Signup</h2>
<label for="email">Email:</label>
<input type="email" />
@@ -208,10 +221,9 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `
- <div class="plausible-event-name=Form+Submit">
+ bodyContent: /* HTML */ ` <div class="plausible-event-name=Form+Submit">
<form action="https://example.com/register" method="post">
- <input type="text"/>
+ <input type="text" />
<input type="submit" value="Submit" />
</form>
</div>`
@@ -252,7 +264,10 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<span class="plausible-event-name=Custom+Event plausible-event-foo=bar"><strong>any</strong>text</span>`
+ bodyContent: /* HTML */ `<span
+ class="plausible-event-name=Custom+Event plausible-event-foo=bar"
+ ><strong>any</strong>text</span
+ >`
})
await page.goto(url)
@@ -287,7 +302,11 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<button class="plausible-event-name=Custom+Event plausible-event-foo=bar">✅</button>`
+ bodyContent: /* HTML */ `<button
+ class="plausible-event-name=Custom+Event plausible-event-foo=bar"
+ >
+ ✅
+ </button>`
})
await page.goto(url)
@@ -360,7 +379,7 @@ for (const mode of ['legacy', 'web']) {
const targetPage = await initializePageDynamically(page, {
testId,
scriptConfig: '',
- bodyContent: `<h1>Subscription successful</h1>`,
+ bodyContent: /* HTML */ `<h1>Subscription successful</h1>`,
path: '/target'
})
const { url } = await initializePageDynamically(page, {
@@ -373,7 +392,11 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<a class="plausible-event-name=Subscribe" href="${targetPage.url}">Click to subscribe</a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-name=Subscribe"
+ href="${targetPage.url}"
+ >Click to subscribe</a
+ >`
})
await page.goto(url)
const navigationPromise = page.waitForRequest(targetPage.url, {
@@ -403,7 +426,7 @@ for (const mode of ['legacy', 'web']) {
const targetPage = await initializePageDynamically(page, {
testId,
scriptConfig: '',
- bodyContent: `<h1>Navigation successful</h1>`,
+ bodyContent: /* HTML */ `<h1>Navigation successful</h1>`,
path: '/target'
})
const { url } = await initializePageDynamically(page, {
@@ -416,7 +439,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `
+ bodyContent: /* HTML */ `
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<a class="plausible-event-name=link+click" href="${targetPage.url}">
<circle cx="50" cy="50" r="50" />
@@ -458,7 +481,7 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<button class="anything">✅</button>`
+ bodyContent: /* HTML */ `<button class="anything">✅</button>`
})
await page.goto(url)
@@ -482,7 +505,9 @@ for (const mode of ['legacy', 'web']) {
},
mode
),
- bodyContent: `<span class="plausible-event-name=">anything</span>`
+ bodyContent: /* HTML */ `<span class="plausible-event-name="
+ >anything</span
+ >`
})
await page.goto(url)
@@ -562,7 +587,12 @@ test.describe('tagged events feature when using legacy .compat extension', () =>
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.tagged-events.js"></script>',
- bodyContent: `<a class="plausible-event-name=outbound" ${linkAttributes} href="${outboundUrl}"><h1>➡️</h1></a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-name=outbound"
+ ${linkAttributes}
+ href="${outboundUrl}"
+ ><h1>➡️</h1></a
+ >`
})
await page.goto(url)
@@ -591,14 +621,18 @@ test.describe('tagged events feature when using legacy .compat extension', () =>
const targetPage = await initializePageDynamically(page, {
testId,
scriptConfig: '',
- bodyContent: `<h1>Subscription successful</h1>`,
+ bodyContent: /* HTML */ `<h1>Subscription successful</h1>`,
path: '/target'
})
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.tagged-events.js"></script>',
- bodyContent: `<a class="plausible-event-name=Subscribe" href="${targetPage.url}">Click to subscribe</a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-name=Subscribe"
+ href="${targetPage.url}"
+ >Click to subscribe</a
+ >`
})
await page.goto(url)
const navigationPromise = page.waitForRequest(targetPage.url, {
@@ -635,14 +669,18 @@ test.describe('tagged events feature when using legacy .compat extension', () =>
const targetPage = await initializePageDynamically(page, {
testId,
scriptConfig: '',
- bodyContent: `<h1>Subscription successful</h1>`,
+ bodyContent: /* HTML */ `<h1>Subscription successful</h1>`,
path: '/target'
})
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.tagged-events.js"></script>',
- bodyContent: `<a class="plausible-event-name=Subscribe" href="${targetPage.url}">Click to subscribe</a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-name=Subscribe"
+ href="${targetPage.url}"
+ >Click to subscribe</a
+ >`
})
await page.goto(url)
const navigationPromise = page.waitForRequest(targetPage.url, {
@@ -659,14 +697,18 @@ test.describe('tagged events feature when using legacy .compat extension', () =>
const targetPage = await initializePageDynamically(page, {
testId,
scriptConfig: '',
- bodyContent: `<h1>Subscription successful</h1>`,
+ bodyContent: /* HTML */ `<h1>Subscription successful</h1>`,
path: '/target'
})
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.tagged-events.js"></script>',
- bodyContent: `<a class="plausible-event-key=value" href="${targetPage.url}">Click to subscribe</a>`
+ bodyContent: /* HTML */ `<a
+ class="plausible-event-key=value"
+ href="${targetPage.url}"
+ >Click to subscribe</a
+ >`
})
await page.goto(url)
@@ -684,14 +726,14 @@ test.describe('tagged events feature when using legacy .compat extension', () =>
const targetPage = await initializePageDynamically(page, {
testId,
scriptConfig: '',
- bodyContent: `<h1>Subscription successful</h1>`,
+ bodyContent: /* HTML */ `<h1>Subscription successful</h1>`,
path: '/target'
})
const { url } = await initializePageDynamically(page, {
testId,
scriptConfig:
'<script id="plausible" async src="/tracker/js/plausible.compat.local.manual.tagged-events.js"></script>',
- bodyContent: `
+ bodyContent: /* HTML */ `
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<a class="plausible-event-name=link+click" href="${targetPage.url}">
<circle cx="50" cy="50" r="50" />
diff --git a/tracker/test/transform_request.spec.ts b/tracker/test/transform_request.spec.ts
index 6bbf588d13..7823142e8c 100644
--- a/tracker/test/transform_request.spec.ts
+++ b/tracker/test/transform_request.spec.ts
@@ -80,7 +80,9 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<button onclick="window.plausible('Purchase')">Purchase</button>`
+ bodyContent: /* HTML */ `<button onclick="window.plausible('Purchase')">
+ Purchase
+ </button>`
})
await expectPlausibleInAction(page, {
@@ -119,7 +121,9 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<button onclick="window.plausible('Purchase')">Purchase</button>`
+ bodyContent: /* HTML */ `<button onclick="window.plausible('Purchase')">
+ Purchase
+ </button>`
})
await expectPlausibleInAction(page, {
@@ -137,45 +141,47 @@ for (const mode of ['web', 'esm']) {
})
test('"transformRequest" does not allow making engagement event props different from pageview event props', async ({
- page
- }, { testId }) => {
- const config = {
- ...DEFAULT_CONFIG,
- transformRequest: (payload) => {
- // @ts-expect-error - defines window.requestCount
- window.requestCount = (window.requestCount ?? 0) + 1
- // @ts-expect-error - window.requestCount is defined
- return { ...payload, p: { requestCount: window.requestCount } }
- }
+ page
+ }, { testId }) => {
+ const config = {
+ ...DEFAULT_CONFIG,
+ transformRequest: (payload) => {
+ // @ts-expect-error - defines window.requestCount
+ window.requestCount = (window.requestCount ?? 0) + 1
+ // @ts-expect-error - window.requestCount is defined
+ return { ...payload, p: { requestCount: window.requestCount } }
}
-
- const { url } = await initializePageDynamically(page, {
- testId,
- scriptConfig: switchByMode(
- {
- web: config,
- esm: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; init(${serializeWithFunctions(
- config
- )})</script>`
- },
- mode
- ),
- bodyContent: `<button onclick="window.plausible('Purchase')">Purchase</button>`
- })
-
- await expectPlausibleInAction(page, {
- action: async () => {
- await page.goto(url)
- await page.click('button')
- await hideAndShowCurrentTab(page, { delay: 200 })
+ }
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: config,
+ esm: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; init(${serializeWithFunctions(
+ config
+ )})</script>`
},
- expectedRequests: [
- { n: 'pageview', p: { requestCount: 1 } },
- { n: 'Purchase', p: { requestCount: 2 } },
- { n: 'engagement', p: { requestCount: 1 } }
- ]
- })
- })
+ mode
+ ),
+ bodyContent: /* HTML */ `<button onclick="window.plausible('Purchase')">
+ Purchase
+ </button>`
+ })
+
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await page.goto(url)
+ await page.click('button')
+ await hideAndShowCurrentTab(page, { delay: 200 })
+ },
+ expectedRequests: [
+ { n: 'pageview', p: { requestCount: 1 } },
+ { n: 'Purchase', p: { requestCount: 2 } },
+ { n: 'engagement', p: { requestCount: 1 } }
+ ]
+ })
+ })
test('specificity: "transformRequest" runs after custom properties are determined', async ({
page
@@ -239,7 +245,11 @@ for (const mode of ['web', 'esm']) {
},
mode
),
- bodyContent: `<button onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })">Subscribe</button>`
+ bodyContent: /* HTML */ `<button
+ onclick="window.plausible('subscribed from blog', { props: { title: 'A blog post title' } })"
+ >
+ Subscribe
+ </button>`
})
await expectPlausibleInAction(page, {