Skip to content

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

Script v2: Remove delays except when using .compat extension (#5465)

Artur Pata74dddc241c30
diff --git a/tracker/npm_package/CHANGELOG.md b/tracker/npm_package/CHANGELOG.md
index d5f8ef5f95..31054759f3 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
+- Remove now unnecessary navigation delays on link clicks and form submissions.
+
## [0.2.4] - 2025-06-19
- Add `logging` option
diff --git a/tracker/package.json b/tracker/package.json
index 6410a6aba8..3d3c462330 100644
--- a/tracker/package.json
+++ b/tracker/package.json
@@ -1,5 +1,5 @@
{
- "tracker_script_version": 20,
+ "tracker_script_version": 21,
"type": "module",
"scripts": {
"deploy": "node compile.js",
diff --git a/tracker/playwright.config.js b/tracker/playwright.config.js
index 3be4eb7777..7288966320 100644
--- a/tracker/playwright.config.js
+++ b/tracker/playwright.config.js
@@ -6,7 +6,8 @@ import { defineConfig, devices } from '@playwright/test'
*/
export default defineConfig({
testDir: './test',
- timeout: 60 * 1000,
+ /* Can be overridden in specific tests with test('a longer running test', async () => { test.setTimeout(<longer timeout>); // test content... }) */
+ timeout: 10 * 1000,
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
diff --git a/tracker/src/custom-events.js b/tracker/src/custom-events.js
index c7ec97267f..218b021220 100644
--- a/tracker/src/custom-events.js
+++ b/tracker/src/custom-events.js
@@ -56,6 +56,9 @@ function handleLinkClickEvent(event) {
}
function sendLinkClickEvent(event, link, eventAttrs) {
+ // In some legacy variants, this block delays opening the link up to 5 seconds,
+ // or until analytics request finishes, otherwise navigation prevents the analytics event from being sent.
+ if (COMPILE_COMPAT) {
var followedLink = false
function followLink() {
@@ -80,6 +83,13 @@ function sendLinkClickEvent(event, link, eventAttrs) {
}
track(eventAttrs.name, attrs)
}
+ } else {
+ var attrs = { props: eventAttrs.props }
+ if (COMPILE_REVENUE) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ track(eventAttrs.name, attrs)
+ }
}
function isOutboundLink(link) {
@@ -190,6 +200,9 @@ export function init() {
var eventAttrs = getTaggedEventAttributes(form)
if (!eventAttrs.name) { return }
+ // In some legacy variants, this block delays submitting the form for up to 5 seconds,
+ // or until analytics request finishes, otherwise form-related navigation can prevent the analytics event from being sent.
+ if (COMPILE_COMPAT) {
event.preventDefault()
var formSubmitted = false
@@ -207,6 +220,13 @@ export function init() {
attrs.revenue = eventAttrs.revenue
}
track(eventAttrs.name, attrs)
+ } else {
+ var attrs = { props: eventAttrs.props }
+ if (COMPILE_REVENUE) {
+ attrs.revenue = eventAttrs.revenue
+ }
+ track(eventAttrs.name, attrs)
+ }
}
function isForm(element) {
diff --git a/tracker/test/custom-event-edge-cases.spec.js b/tracker/test/custom-event-edge-cases.spec.js
deleted file mode 100644
index 2cc4170fd0..0000000000
--- a/tracker/test/custom-event-edge-cases.spec.js
+++ /dev/null
@@ -1,45 +0,0 @@
-import { expectPlausibleInAction } from './support/test-utils'
-import { test } from '@playwright/test'
-import { LOCAL_SERVER_ADDR } from './support/server'
-
-test.describe('script.file-downloads.outbound-links.tagged-events.js', () => {
- test('sends only outbound link event when clicked link is both download and outbound', async ({ page }) => {
- await page.goto('/custom-event-edge-case.html')
- const downloadURL = await page.locator('#outbound-download-link').getAttribute('href')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#outbound-download-link'),
- expectedRequests: [{ n: 'Outbound Link: Click', p: { url: downloadURL } }]
- })
- })
-
- test('sends file download event when local download link clicked', async ({ page }) => {
- await page.goto('/custom-event-edge-case.html')
- const downloadURL = LOCAL_SERVER_ADDR + '/' + await page.locator('#local-download').getAttribute('href')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#local-download'),
- expectedRequests: [{ n: 'File Download', p: { url: downloadURL } }]
- })
- })
-
- test('sends only tagged event when clicked link is tagged + outbound + download', async ({ page }) => {
- await page.goto('/custom-event-edge-case.html')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#tagged-outbound-download-link'),
- expectedRequests: [{ n: 'Foo', p: { url: 'https://awesome.website.com/file.pdf' } }],
- awaitedRequestCount: 3,
- expectedRequestCount: 1
- })
- })
-
- test('sends manual non-interactive custom event', async ({ page }) => {
- await page.goto('/custom-event-edge-case.html')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#non-interactive-custom-event'),
- expectedRequests: [{ n: 'non-interactive custom event', i: false }]
- })
- })
-})
diff --git a/tracker/test/features-hierarchy-on-overlap.spec.ts b/tracker/test/features-hierarchy-on-overlap.spec.ts
new file mode 100644
index 0000000000..17796f4019
--- /dev/null
+++ b/tracker/test/features-hierarchy-on-overlap.spec.ts
@@ -0,0 +1,151 @@
+import { expectPlausibleInAction, switchByMode } from './support/test-utils'
+import { test, expect } from '@playwright/test'
+import { LOCAL_SERVER_ADDR } from './support/server'
+import { initializePageDynamically } from './support/initialize-page-dynamically'
+import { mockManyRequests } from './support/mock-many-requests'
+import { ScriptConfig } from './support/types'
+
+const DEFAULT_CONFIG: ScriptConfig = {
+ domain: 'example.com',
+ endpoint: `${LOCAL_SERVER_ADDR}/api/event`,
+ captureOnLocalhost: true
+}
+
+for (const mode of ['legacy', 'web']) {
+ test.describe(`outbound links, file downloads, tagged events features hierarchy on overlap legacy/v2 parity (${mode})`, () => {
+ test('sends only tagged event if the link is a tagged outbound download link', async ({
+ page
+ }, { testId }) => {
+ const downloadUrl = 'https://files.example.com/file.pdf'
+ const downloadMock = await mockManyRequests({
+ page,
+ path: downloadUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'application/pdf',
+ body: 'mocked pdf content'
+ },
+ awaitedRequestCount: 1
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ autoCapturePageviews: false,
+ outboundLinks: true,
+ fileDownloads: true
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.manual.outbound-links.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a class="plausible-event-name=Custom+Event" href="${downloadUrl}">Outbound Download</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ expectedRequests: [{ n: 'Custom Event', p: { url: downloadUrl } }],
+ awaitedRequestCount: 2
+ })
+
+ await expect(downloadMock.getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('sends only outbound link event if the link is an outbound download link', async ({
+ page
+ }, { testId }) => {
+ const downloadUrl = 'https://files.example.com/file.pdf'
+ const downloadMock = await mockManyRequests({
+ page,
+ path: downloadUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'application/pdf',
+ body: 'mocked pdf content'
+ },
+ awaitedRequestCount: 1
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ autoCapturePageviews: false,
+ outboundLinks: true,
+ fileDownloads: true
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.manual.outbound-links.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${downloadUrl}">Get file</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ expectedRequests: [
+ { n: 'Outbound Link: Click', p: { url: downloadUrl } }
+ ],
+ awaitedRequestCount: 2
+ })
+ await expect(downloadMock.getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('sends file download event when local download link is clicked', async ({
+ page
+ }, { testId }) => {
+ const downloadUrl = '/file.pdf'
+ const downloadMock = await mockManyRequests({
+ page,
+ path: downloadUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'application/pdf',
+ body: 'mocked pdf content'
+ },
+ awaitedRequestCount: 1
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ autoCapturePageviews: false,
+ outboundLinks: true,
+ fileDownloads: true
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.manual.outbound-links.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${downloadUrl}">Get file</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ expectedRequests: [
+ {
+ n: 'File Download',
+ p: { url: `${LOCAL_SERVER_ADDR}${downloadUrl}` }
+ }
+ ],
+ awaitedRequestCount: 2
+ })
+
+ await expect(downloadMock.getRequestList()).resolves.toHaveLength(1)
+ })
+ })
+}
diff --git a/tracker/test/file-downloads.spec.js b/tracker/test/file-downloads.spec.js
index 49d147872b..e69de29bb2 100644
--- a/tracker/test/file-downloads.spec.js
+++ b/tracker/test/file-downloads.spec.js
@@ -1,129 +0,0 @@
-import { mockRequest, metaKey, expectPlausibleInAction } from './support/test-utils'
-import { expect, test } from '@playwright/test'
-import { LOCAL_SERVER_ADDR } from './support/server'
-
-test.describe('legacy file-downloads extension', () => {
- test('sends event and does not start download when link opens in new tab', async ({ page }) => {
- await page.goto('/file-download.html')
- const downloadURL = await page.locator('#link').getAttribute('href')
-
- const downloadRequestMock = mockRequest(page, downloadURL)
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link', { modifiers: [metaKey()] }),
- expectedRequests: [{n: 'File Download', p: { url: downloadURL }}]
- })
-
- expect(await downloadRequestMock, "should not make download request").toBeNull()
- })
-
- test('sends event and starts download when link child is clicked', async ({ page }) => {
- await page.goto('/file-download.html')
- const downloadURL = await page.locator('#link').getAttribute('href')
-
- const downloadRequestMock = mockRequest(page, downloadURL)
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link-child'),
- expectedRequests: [{n: 'File Download', p: { url: downloadURL }}]
- })
-
- expect((await downloadRequestMock).url()).toContain(downloadURL)
- })
-
- test('sends File Download event with query-stripped url property', async ({ page }) => {
- await page.goto('/file-download.html')
- const downloadURL = await page.locator('#link-query').getAttribute('href')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link-query'),
- expectedRequests: [{n: 'File Download', p: { url: downloadURL.split("?")[0] }}]
- })
- })
-
- test('starts download only once', async ({ page }) => {
- await page.goto('/file-download.html')
- const downloadURL = LOCAL_SERVER_ADDR + '/' + await page.locator('#local-download').getAttribute('href')
- const timeToWaitMs = 3000
- let requestCount = 0
- await page.route(downloadURL, async (route) => {
- requestCount++
- await route.fulfill({
- status: 202,
- contentType: 'text/plain',
- body: 'ok'
- })
- })
- await page.click('#local-download')
- await new Promise(resolve => setTimeout(resolve, timeToWaitMs))
- expect(requestCount).toBe(1)
- })
-})
-
-
-test.describe('file downloads', () => {
- test.beforeEach(({ page }) => {
- // Mock file download requests
- mockRequest(page, 'https://awesome.website.com/file.iso')
- })
-
- const DEFAULT_CONFIG = {
- domain: 'example.com',
- endpoint: `${LOCAL_SERVER_ADDR}/api/event`,
- captureOnLocalhost: true,
- autoCapturePageviews: false
- }
-
- async function openPage(page, config) {
- await page.goto(`/file-download-plausible-web.html`)
- await page.waitForFunction('window.plausible !== undefined')
-
- await page.evaluate((config) => {
- window.plausible.init(config)
- }, { ...DEFAULT_CONFIG, ...config })
- }
-
- test('does not track iso files by default', async ({ page }) => {
- await openPage(page, { fileDownloads: true })
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#file-download-iso', { modifiers: [metaKey()] }),
- expectedRequests: [],
- rejectRequests: [{ n: 'File Download' }],
- })
- })
-
- test('tracks iso but not pdf files when config.fileDownloads includes "iso"', async ({ page }) => {
- await openPage(page, { fileDownloads: { fileExtensions: ['iso'] } })
-
- await expectPlausibleInAction(page, {
- action: async () => {
- await page.click('#file-download-iso', { modifiers: [metaKey()] })
- await page.click('#file-download', { modifiers: [metaKey()] })
- },
- expectedRequests: [
- { n: 'File Download', p: { url: 'https://awesome.website.com/file.iso' } },
- ],
- rejectRequests: [
- { n: 'File Download', p: { url: 'https://awesome.website.com/file.pdf' } },
- ]
- })
- })
-
- test('ignores malformed value but enables the feature', async ({ page }) => {
- await openPage(page, { fileDownloads: { fileExtensions: 'iso' } })
-
- await expectPlausibleInAction(page, {
- action: async () => {
- await page.click('#file-download-iso', { modifiers: [metaKey()] })
- await page.click('#file-download', { modifiers: [metaKey()] })
- },
- expectedRequests: [
- { n: 'File Download', p: { url: 'https://awesome.website.com/file.pdf' } },
- ],
- rejectRequests: [
- { n: 'File Download', p: { url: 'https://awesome.website.com/file.iso' } },
- ]
- })
- })
-})
diff --git a/tracker/test/file-downloads.spec.ts b/tracker/test/file-downloads.spec.ts
new file mode 100644
index 0000000000..8d5d6a1523
--- /dev/null
+++ b/tracker/test/file-downloads.spec.ts
@@ -0,0 +1,601 @@
+import {
+ expectPlausibleInAction,
+ isPageviewEvent,
+ isEngagementEvent,
+ switchByMode
+} from './support/test-utils'
+import { expect, test } from '@playwright/test'
+import { LOCAL_SERVER_ADDR } from './support/server'
+import { initializePageDynamically } from './support/initialize-page-dynamically'
+import { ScriptConfig } from './support/types'
+import {
+ mockManyRequests,
+ resolveWithTimestamps
+} from './support/mock-many-requests'
+
+const DEFAULT_CONFIG: ScriptConfig = {
+ domain: 'example.com',
+ endpoint: `${LOCAL_SERVER_ADDR}/api/event`,
+ captureOnLocalhost: true
+}
+
+for (const mode of ['legacy', 'web']) {
+ test.describe(`file downloads feature legacy/v2 parity (${mode})`, () => {
+ test('tracks download when link opens in same tab', async ({ page }, {
+ testId
+ }) => {
+ const filePath = '/file.csv'
+ const { getRequestList } = await mockManyRequests({
+ page,
+ path: `${LOCAL_SERVER_ADDR}${filePath}`,
+ fulfill: {
+ contentType: 'text/csv'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, fileDownloads: true },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${filePath}">📥</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ expectedRequests: [
+ { n: 'File Download', p: { url: `${LOCAL_SERVER_ADDR}${filePath}` } }
+ ],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expect(getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('tracks download when link opens in new tab (target="_blank")', async ({
+ page
+ }, { testId }) => {
+ const pdfUrl = 'https://example.com/downloads/file.pdf'
+ const pdfMock = await mockManyRequests({
+ page,
+ path: pdfUrl,
+ fulfill: {
+ contentType: 'application/pdf'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, fileDownloads: true },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${pdfUrl}" target="_blank">📥</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ expectedRequests: [{ n: 'File Download', p: { url: pdfUrl } }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expect(pdfMock.getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('tracks download when link opens in new tab (ControlOrMeta + click)', async ({
+ page,
+ browserName
+ }, { testId }) => {
+ test.skip(
+ browserName === 'webkit',
+ 'does not start downloads properly with such clicks (works when testing manually in macOS Safari)'
+ )
+ const pdfUrl = 'https://example.com/downloads/file.pdf'
+ const pdfMock = await mockManyRequests({
+ page,
+ path: pdfUrl,
+ fulfill: {
+ contentType: 'application/pdf'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, fileDownloads: true },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${pdfUrl}">📥</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a', { modifiers: ['ControlOrMeta'] }),
+ expectedRequests: [{ n: 'File Download', p: { url: pdfUrl } }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expect(pdfMock.getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('tracks download when link child element is clicked', async ({
+ page
+ }, { testId }) => {
+ const pdfUrl = 'https://example.com/downloads/file.pdf'
+ const pdfMock = await mockManyRequests({
+ page,
+ path: pdfUrl,
+ fulfill: {
+ contentType: 'application/pdf'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, fileDownloads: true },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${pdfUrl}"><div><span>📥</span></div></a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('span'),
+ expectedRequests: [{ n: 'File Download', p: { url: pdfUrl } }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expect(pdfMock.getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('tracks download without delaying navigation, relying on fetch options.keepalive to deliver tracking events', async ({
+ page
+ }, { testId }) => {
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 500
+ })
+ const pdfUrl = 'https://example.com/downloads/file.pdf'
+ const pdfMock = await mockManyRequests({
+ page,
+ path: pdfUrl,
+ fulfill: {
+ contentType: 'application/pdf'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ fileDownloads: true,
+ autoCapturePageviews: false
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.manual.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${pdfUrl}">Download</a>`
+ })
+ await page.goto(url)
+ await page.click('a')
+ const [
+ [trackingRequestList, trackingResponseTime],
+ [downloadMockRequestList, downloadRequestTime]
+ ] = await resolveWithTimestamps([
+ eventsApiMock.getRequestList(),
+ pdfMock.getRequestList()
+ ])
+
+ expect(downloadRequestTime).toBeLessThan(trackingResponseTime)
+ expect(downloadMockRequestList).toHaveLength(1)
+ expect(trackingRequestList).toEqual([
+ expect.objectContaining({
+ n: 'File Download',
+ p: {
+ url: pdfUrl
+ }
+ })
+ ])
+ })
+
+ test('event.props.url is stripped of query parameters', async ({ page }, {
+ testId
+ }) => {
+ const pdfUrl = 'https://example.com/downloads/file.pdf'
+ const pdfMock = await mockManyRequests({
+ page,
+ path: `${pdfUrl}*`,
+ fulfill: {
+ contentType: 'application/pdf'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, fileDownloads: true },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${pdfUrl}?user=foo%secret=123">Download PDF</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ expectedRequests: [{ n: 'File Download', p: { url: pdfUrl } }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expect(pdfMock.getRequestList()).resolves.toHaveLength(1)
+ })
+
+ test('does not track iso files by default', async ({ page }, {
+ testId
+ }) => {
+ await mockManyRequests({
+ page,
+ path: 'https://example.com/file.iso',
+ fulfill: {
+ contentType: 'application/octet-stream'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, fileDownloads: true },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="https://example.com/file.iso">📥</a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ refutedRequests: [{ n: 'File Download' }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('respects file download whitelist ["iso"]', async ({ page }, {
+ testId
+ }) => {
+ const csvFileURL = `https://example.com/file.csv`
+ const isoFileURL = `https://example.com/file.iso`
+ const csvMock = await mockManyRequests({
+ page,
+ path: csvFileURL,
+ fulfill: {
+ contentType: 'text/csv'
+ },
+ awaitedRequestCount: 1
+ })
+ const isoMock = await mockManyRequests({
+ page,
+ path: isoFileURL,
+ fulfill: {
+ contentType: 'application/octet-stream'
+ },
+ awaitedRequestCount: 1
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ fileDownloads: { fileExtensions: ['iso'] }
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.file-downloads.local.js" file-types="iso"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${isoFileURL}" target="_blank">📥</a><a href="${csvFileURL}" target="_blank">📥</a>`
+ })
+ await page.goto(url)
+ await expectPlausibleInAction(page, {
+ action: () => page.click(`a[href="${csvFileURL}"]`),
+ refutedRequests: [{ n: 'File Download' }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ await expect(csvMock.getRequestList()).resolves.toHaveLength(1)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click(`a[href="${isoFileURL}"]`),
+ expectedRequests: [{ n: 'File Download', p: { url: isoFileURL } }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ await expect(isoMock.getRequestList()).resolves.toHaveLength(1)
+ })
+ })
+}
+
+for (const mode of ['web', 'esm']) {
+ test.describe(`file downloads feature v2-specific (${mode})`, () => {
+ test('malformed `fileDownloads: "iso"` option enables the feature with default file types', async ({
+ page
+ }, { testId }) => {
+ const csvFileURL = `https://example.com/file.csv`
+ const isoFileURL = `https://example.com/file.iso`
+
+ const csvMock = await mockManyRequests({
+ page,
+ path: csvFileURL,
+ fulfill: {
+ contentType: 'text/csv'
+ },
+ awaitedRequestCount: 1
+ })
+ const isoMock = await mockManyRequests({
+ page,
+ path: isoFileURL,
+ fulfill: {
+ contentType: 'application/octet-stream'
+ },
+ awaitedRequestCount: 1
+ })
+
+ const config = {
+ ...DEFAULT_CONFIG,
+ fileDownloads: 'iso'
+ }
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: config,
+ esm: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; window.init = init; window.track = track; init(${JSON.stringify(
+ config
+ )})</script>`
+ },
+ mode
+ ),
+ bodyContent: `<a href="${isoFileURL}" target="_blank">📥</a><a href="${csvFileURL}" target="_blank">📥</a>`
+ })
+ await page.goto(url)
+ await expectPlausibleInAction(page, {
+ action: () => page.click(`a[href="${csvFileURL}"]`),
+ expectedRequests: [{ n: 'File Download', p: { url: csvFileURL } }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ await expect(csvMock.getRequestList()).resolves.toHaveLength(1)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click(`a[href="${isoFileURL}"]`),
+ refutedRequests: [{ n: 'File Download' }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ await expect(isoMock.getRequestList()).resolves.toHaveLength(1)
+ })
+ })
+}
+
+test.describe('file downloads feature when using legacy .compat extension', () => {
+ for (const { clickName, linkAttributes, click, expected, skip } of [
+ {
+ clickName: 'when left clicking on link',
+ linkAttributes: '',
+ click: { element: 'a' },
+ expected: { downloadsOnSamePage: 1, downloadsOnOtherPages: 0 }
+ },
+ {
+ clickName: 'when left clicking on link with Ctrl or Meta key',
+ linkAttributes: '',
+ click: { element: 'a', modifiers: ['ControlOrMeta' as const] },
+ expected: { downloadsOnSamePage: 0, downloadsOnOtherPages: 1 },
+ skip: (browserName) =>
+ test.skip(
+ browserName === 'webkit',
+ 'does not open links with such clicks (works when testing manually in macOS Safari)'
+ )
+ },
+ {
+ clickName: 'when left clicking on child element of target="_blank" link',
+ linkAttributes: 'target="_blank"',
+ click: { element: 'a[target="_blank"] > h1' },
+ expected: { downloadsOnSamePage: 0, downloadsOnOtherPages: 1 }
+ }
+ ]) {
+ test(`tracks and starts exactly one download ${clickName}`, async ({
+ page,
+ browserName
+ }, { testId }) => {
+ if (skip) {
+ skip(browserName)
+ }
+
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 2,
+ mockRequestTimeout: 2000
+ })
+ const filePath = '/file.csv'
+ const downloadMockOptions = {
+ page,
+ path: `${LOCAL_SERVER_ADDR}${filePath}`,
+ fulfill: {
+ contentType: 'text/csv'
+ },
+ awaitedRequestCount: 2,
+ mockRequestTimeout: 2000
+ }
+
+ const downloadMockForOtherPages = await mockManyRequests({
+ ...downloadMockOptions,
+ scopeMockToPage: false
+ })
+ const downloadMockForSamePage = await mockManyRequests({
+ ...downloadMockOptions,
+ scopeMockToPage: true
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.file-downloads.local.manual.js"></script>',
+ bodyContent: `<a ${linkAttributes} href="${filePath}"><h1>📥</h1></a>`
+ })
+ await page.goto(url)
+ await page.click(click.element, { modifiers: click.modifiers })
+ const [downloadsOnSamePage, downloadsOnOtherPages, eventsApiRequests] =
+ await Promise.all([
+ downloadMockForSamePage.getRequestList().then((d) => d.length),
+ downloadMockForOtherPages.getRequestList().then((d) => d.length),
+ eventsApiMock.getRequestList()
+ ])
+ expect({
+ downloadsOnSamePage,
+ downloadsOnOtherPages
+ }).toEqual(expected)
+ expect(eventsApiRequests).toEqual([
+ expect.objectContaining({
+ n: 'File Download',
+ p: {
+ url: `${LOCAL_SERVER_ADDR}${filePath}`
+ }
+ })
+ ])
+ })
+ }
+
+ for (const { fulfill } of [
+ {
+ fulfill: {
+ status: 202,
+ contentType: 'text/plain',
+ body: 'ok'
+ }
+ },
+ {
+ fulfill: {
+ status: 400,
+ contentType: 'text/plain',
+ body: 'Bad Request'
+ }
+ }
+ ]) {
+ test(`tracking delays navigation until the tracking request has finished (with status: ${fulfill.status})`, async ({
+ page
+ }, { testId }) => {
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ fulfill,
+ awaitedRequestCount: 1,
+ responseDelay: 1000
+ })
+ const filePath = '/file.csv'
+ const downloadableFileMock = await mockManyRequests({
+ page,
+ path: `${LOCAL_SERVER_ADDR}${filePath}`,
+ fulfill: {
+ contentType: 'text/csv'
+ },
+ awaitedRequestCount: 1,
+ mockRequestTimeout: 1000
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.file-downloads.local.manual.js"></script>',
+ bodyContent: `<a href="${filePath}">📥</a>`
+ })
+ await page.goto(url)
+
+ const navigationPromise = page.waitForRequest(filePath, {
+ timeout: 2000
+ })
+ const trackingPromise = page.waitForResponse('**/api/event', {
+ timeout: 2000
+ })
+
+ await page.click('a')
+ const [[, trackingResponseTime], [, navigationTime]] =
+ await resolveWithTimestamps([trackingPromise, navigationPromise])
+ await expect(downloadableFileMock.getRequestList()).resolves.toHaveLength(
+ 1
+ )
+ expect(trackingResponseTime).toBeLessThanOrEqual(navigationTime)
+ await expect(eventsApiMock.getRequestList()).resolves.toEqual([
+ expect.objectContaining({
+ n: 'File Download',
+ p: {
+ url: `${LOCAL_SERVER_ADDR}${filePath}`
+ }
+ })
+ ])
+ })
+ }
+
+ test('if the tracking requests delays navigation for more than 5s, it navigates anyway, without waiting for the request to resolve ', async ({
+ page
+ }, { testId }) => {
+ test.setTimeout(20000)
+ await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 6000
+ })
+ const filePath = '/file.csv'
+ const downloadableFileMock = await mockManyRequests({
+ page,
+ path: `${LOCAL_SERVER_ADDR}${filePath}`,
+ fulfill: {
+ contentType: 'text/csv'
+ },
+ awaitedRequestCount: 1,
+ mockRequestTimeout: 1000
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.file-downloads.local.manual.js"></script>',
+ bodyContent: `<a href="${filePath}">📥</a>`
+ })
+ await page.goto(url)
+ const navigationPromise = page.waitForRequest(filePath, {
+ timeout: 6000
+ })
+ await page.click('a')
+ await navigationPromise
+ await expect(downloadableFileMock.getRequestList()).resolves.toHaveLength(1)
+ })
+})
diff --git a/tracker/test/fixtures/custom-event-edge-case.html b/tracker/test/fixtures/custom-event-edge-case.html
deleted file mode 100644
index 245f33e331..0000000000
--- a/tracker/test/fixtures/custom-event-edge-case.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Plausible Playwright tests</title>
-
- <script defer src="/tracker/js/plausible.file-downloads.local.manual.outbound-links.tagged-events.js"></script>
-</head>
-
-<body>
- <a id="outbound-download-link" href="https://awesome.website.com/file.pdf">Outbound Download</a>
-
- <a id="local-download" href="file.csv">Local download</a>
-
- <a id="tagged-outbound-download-link" class="plausible-event-name=Foo" href="https://awesome.website.com/file.pdf">Outbound Download</a>
-
- <a id="non-interactive-custom-event" onclick="plausible('non-interactive custom event', { interactive: false })">Non-interactive custom event</a>
-</body>
-
-</html>
diff --git a/tracker/test/fixtures/file-download.html b/tracker/test/fixtures/file-download.html
deleted file mode 100644
index 22aa8e3977..0000000000
--- a/tracker/test/fixtures/file-download.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Plausible Playwright tests</title>
-
- <script defer src="/tracker/js/plausible.file-downloads.local.manual.js" add-file-types="ex,exs"></script>
-</head>
-
-<body>
- <a id="link" href="https://awesome.website.com/file.pdf">
- <span id="link-child">Download</span>
- </a>
-
- <a id="link-query" href="https://awesome.website.com/file.ex?some=query">Download link with query</a>
-
- <a id="local-download" href="file.csv">Local download</a>
-</body>
-
-</html>
diff --git a/tracker/test/fixtures/hash-exclusions.html b/tracker/test/fixtures/hash-exclusions.html
deleted file mode 100644
index 2c2feba34d..0000000000
--- a/tracker/test/fixtures/hash-exclusions.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Plausible Playwright tests</title>
- <script defer data-exclude='/*#*/hash/**/ignored' src="/tracker/js/plausible.exclusions.hash.local.js"></script>
-</head>
-
-<body>
- HELLO!
-</body>
-
-</html>
diff --git a/tracker/test/fixtures/outbound-link.html b/tracker/test/fixtures/outbound-link.html
deleted file mode 100644
index 357adf2ec7..0000000000
--- a/tracker/test/fixtures/outbound-link.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Plausible Playwright tests</title>
-
- <script defer src="/tracker/js/plausible.local.manual.outbound-links.js"></script>
-</head>
-
-<body>
- <a id="link" href="https://awesome.website.com/">
- <span id="link-child">Outbound</span>
- </a>
- <a id="link-default-prevented" href="https://awesome.website.com/">Link (default prevented)</a>
- <script>
- document.getElementById('link-default-prevented').addEventListener('click', (e) => {
- e.preventDefault()
- alert('Default prevented by external script')
- })
- </script>
-</body>
-
-</html>
diff --git a/tracker/test/fixtures/simple.html b/tracker/test/fixtures/simple.html
deleted file mode 100644
index 9e24ba114d..0000000000
--- a/tracker/test/fixtures/simple.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Plausible Playwright tests</title>
- <script defer src="/tracker/js/plausible.local.js"></script>
-</head>
-
-<body>
- HELLO!
-</body>
-
-</html>
diff --git a/tracker/test/fixtures/tagged-event.html b/tracker/test/fixtures/tagged-event.html
deleted file mode 100644
index 61b8b8cc29..0000000000
--- a/tracker/test/fixtures/tagged-event.html
+++ /dev/null
@@ -1,81 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Plausible Playwright tests</title>
-
- <script defer src="/tracker/js/plausible.local.manual.tagged-events.js"></script>
-</head>
-
-<body>
- <a id="link"
- class="plausible-event-name--Payment+Complete should ignore-this plausible-event-amount--100 plausible-event-method--Credit+Card"
- href="https://awesome.website.com/payment/">tagged link</a>
-
- <form class="plausible-event-name=Signup plausible-event-type=Newsletter"
- action="https://awesome.website.com/register" method="post">
- <input type="text" id='form-text-input' />
- <input id="form-submit" type="submit" value="Submit" />
- </form>
-
- <button id="button" class="plausible-event-name=Custom+Event plausible-event-foo=bar">
- Button
- </button>
-
- <span id="span" class="plausible-event-name=Custom+Event plausible-event-foo=bar">
- Span
- </span>
-
- <div id="div" class="plausible-event-name=Custom+Event plausible-event-foo=bar">
- <a id="link-with-div-parent" href="https://awesome.website.com/payment/">Div child</a>
- </div>
-
- <a class="plausible-event-name=Custom+Event plausible-event-foo=bar" href="https://awesome.website.com/payment/">
- <h2 id="h2-with-link-parent">Link child</h2>
- </a>
-
- <div class="plausible-event-name=Form+Submit">
- <form action="https://awesome.website.com/register" method="post">
- <input type="text" value="Form" />
- <input id="submit-form-with-tagged-parent" type="submit" value="Submit" />
- </form>
- </div>
-
- <a id="not-tracked-link" class="plausible-event-amount=100 plausible-event-method=Credit+Card"
- href="https://awesome.website.com/payment/">
- Link (without plausible-event-name class)
- </a>
-
- <button id="not-tracked-button" class="im not tracked">
- Button (without plausible-event-name class)
- </button>
-
- <span id="not-tracked-span" class="plausible-event-name= still not tracked">
- Span (without plausible-event-name class)
- </span>
-
-
-
- <script>
- // Dynamically add a tagged element to DOM after one second
- setTimeout(function () {
- let taggedElement = document.createElement('button')
- taggedElement.id = 'dynamic-tagged-button'
- taggedElement.classList.add('plausible-event-name=Custom+Event')
- taggedElement.innerHTML += 'Dynamic tagged button'
- document.body.appendChild(taggedElement)
- }, 1000)
- </script>
-
- <form id="form" class="plausible-event-name=Signup plausible-event-type=Newsletter"
- action="https://awesome.website.com/register" method="post">
- <input type="text" id='form-input' />
- <div id="form-div">div in a form</div>
- <input type="submit" value="Submit" />
- </form>
-</body>
-
-</html>
diff --git a/tracker/test/hash-exclusions.spec.js b/tracker/test/hash-exclusions.spec.js
deleted file mode 100644
index f6a1a21ce1..0000000000
--- a/tracker/test/hash-exclusions.spec.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { mockRequest } from './support/test-utils'
-import { expect, test } from '@playwright/test'
-
-test.describe('combination of hash and exclusions script extensions', () => {
- test('excludes by hash part of the URL', async ({ page }) => {
- const plausibleRequestMock = mockRequest(page, '/api/event')
-
- await page.goto('/hash-exclusions.html#this/hash/should/be/ignored')
-
- expect(await plausibleRequestMock, "should not have sent event").toBeNull()
- })
-})
diff --git a/tracker/test/hash-exclusions.spec.ts b/tracker/test/hash-exclusions.spec.ts
new file mode 100644
index 0000000000..e9e4315eaa
--- /dev/null
+++ b/tracker/test/hash-exclusions.spec.ts
@@ -0,0 +1,18 @@
+import { initializePageDynamically } from './support/initialize-page-dynamically'
+import { expectPlausibleInAction } from './support/test-utils'
+import { test } from '@playwright/test'
+
+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 defer data-exclude='/**#*/hash/**/ignored' src="/tracker/js/plausible.exclusions.hash.local.js"></script>`,
+ bodyContent: ''
+ })
+ await expectPlausibleInAction(page, {
+ action: () => page.goto(`${url}#this/hash/should/be/ignored`),
+ expectedRequests: [],
+ awaitedRequestCount: 1
+ })
+ })
+})
diff --git a/tracker/test/manual.spec.js b/tracker/test/manual.spec.js
index 31ca2d7a55..7c2615b505 100644
--- a/tracker/test/manual.spec.js
+++ b/tracker/test/manual.spec.js
@@ -36,4 +36,12 @@ test.describe('manual extension', () => {
expectedRequests: [{n: 'CustomEvent', u: `https://example.com/custom/location`}]
})
})
+
+ 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}]
+ })
+ })
})
diff --git a/tracker/test/outbound-links.spec.js b/tracker/test/outbound-links.spec.js
deleted file mode 100644
index 5e869cbe80..0000000000
--- a/tracker/test/outbound-links.spec.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import { mockRequest, metaKey, expectPlausibleInAction } from './support/test-utils'
-import { expect, test } from '@playwright/test'
-
-test.describe('outbound-links extension', () => {
- test('sends event and does not navigate when link opens in new tab', async ({ page }) => {
- await page.goto('/outbound-link.html')
- const outboundURL = await page.locator('#link').getAttribute('href')
-
- const navigationRequestMock = mockRequest(page, outboundURL)
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link', { modifiers: [metaKey()] }),
- expectedRequests: [{n: 'Outbound Link: Click', p: { url: outboundURL }}]
- })
-
- expect(await navigationRequestMock, "should not have made navigation request").toBeNull()
- })
-
- test('sends event and navigates to target when link child is clicked', async ({ page }) => {
- await page.goto('/outbound-link.html')
- const outboundURL = await page.locator('#link').getAttribute('href')
-
- const navigationRequestMock = mockRequest(page, outboundURL)
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link-child'),
- expectedRequests: [{n: 'Outbound Link: Click', p: { url: outboundURL }}]
- })
-
- const navigationRequest = await navigationRequestMock
- expect(navigationRequest.url()).toContain(outboundURL)
- })
-
- test('sends event and does not navigate if default externally prevented', async ({ page }) => {
- await page.goto('/outbound-link.html')
- const outboundURL = await page.locator('#link-default-prevented').getAttribute('href')
-
- const navigationRequestMock = mockRequest(page, outboundURL)
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link-default-prevented'),
- expectedRequests: [{n: 'Outbound Link: Click', p: { url: outboundURL }}]
- })
-
- expect(await navigationRequestMock, "should not have made navigation request").toBeNull()
- })
-})
diff --git a/tracker/test/outbound-links.spec.ts b/tracker/test/outbound-links.spec.ts
new file mode 100644
index 0000000000..172ba79dc3
--- /dev/null
+++ b/tracker/test/outbound-links.spec.ts
@@ -0,0 +1,316 @@
+import { initializePageDynamically } from './support/initialize-page-dynamically'
+import {
+ mockManyRequests,
+ resolveWithTimestamps
+} from './support/mock-many-requests'
+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'
+
+const DEFAULT_CONFIG: ScriptConfig = {
+ domain: 'example.com',
+ endpoint: `${LOCAL_SERVER_ADDR}/api/event`,
+ captureOnLocalhost: true
+}
+
+for (const mode of ['legacy', 'web'])
+ test.describe(`outbound links feature legacy/v2 parity (${mode})`, () => {
+ for (const { clickName, click, skip } of [
+ {
+ clickName: 'when left clicking on link',
+ click: { element: 'a' }
+ },
+ {
+ clickName: 'when left clicking on link with Ctrl or Meta key',
+ click: { element: 'a', modifiers: ['ControlOrMeta' as const] },
+ skip: (browserName) =>
+ test.skip(
+ browserName === 'webkit',
+ 'does not open links with such clicks (works when testing manually in macOS Safari)'
+ )
+ },
+ {
+ clickName: 'when left clicking on child element of link',
+ click: { element: 'a > h1' }
+ }
+ ]) {
+ test(`sends event ${clickName}`, async ({ page, browserName }, {
+ testId
+ }) => {
+ if (skip) {
+ skip(browserName)
+ }
+ const outboundUrl = 'https://other.example.com/target'
+ const outboundMock = await mockManyRequests({
+ page,
+ path: outboundUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>other page</title></head><body>other page</body></html>'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ autoCapturePageviews: false,
+ outboundLinks: true
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.manual.outbound-links.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${outboundUrl}"><h1>➡️</h1></a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () =>
+ page.click(click.element, { modifiers: click.modifiers }),
+ expectedRequests: [
+ { n: 'Outbound Link: Click', p: { url: outboundUrl } }
+ ]
+ })
+
+ await expect(outboundMock.getRequestList()).resolves.toHaveLength(1)
+ })
+ }
+
+ test('tracks links without delaying navigation, relying on fetch options.keepalive to deliver tracking events', async ({
+ page
+ }, { testId }) => {
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 500
+ })
+ const outboundUrl = 'https://other.example.com/target'
+ const outboundMock = await mockManyRequests({
+ page,
+ path: outboundUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>other page</title></head><body>other page</body></html>'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: {
+ ...DEFAULT_CONFIG,
+ outboundLinks: true,
+ autoCapturePageviews: false
+ },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.manual.outbound-links.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a href="${outboundUrl}">>➡️</a>`
+ })
+ await page.goto(url)
+ await page.click('a')
+ const [
+ [trackingRequestList, trackingResponseTime],
+ [outboundMockRequestList, outboundRequestTime]
+ ] = await resolveWithTimestamps([
+ eventsApiMock.getRequestList(),
+ outboundMock.getRequestList()
+ ])
+
+ expect(outboundRequestTime).toBeLessThan(trackingResponseTime)
+ expect(outboundMockRequestList).toHaveLength(1)
+ expect(trackingRequestList).toEqual([
+ expect.objectContaining({
+ n: 'Outbound Link: Click',
+ p: {
+ url: outboundUrl
+ }
+ })
+ ])
+ })
+ })
+
+test.describe('outbound links feature when using legacy .compat extension', () => {
+ for (const { caseName, linkAttributes, click, expected, skip } of [
+ {
+ caseName: 'navigates when left clicking on link',
+ linkAttributes: '',
+ click: { element: 'a' },
+ expected: { requestsOnSamePage: 1, requestsOnOtherPages: 0 }
+ },
+ {
+ caseName: 'navigates when left clicking on link with Ctrl or Meta key',
+ linkAttributes: '',
+ click: { element: 'a', modifiers: ['ControlOrMeta' as const] },
+ expected: { requestsOnSamePage: 0, requestsOnOtherPages: 1 },
+ skip: (browserName) =>
+ test.skip(
+ browserName === 'webkit',
+ 'does not open links with such clicks (works when testing manually in macOS Safari)'
+ )
+ },
+ {
+ caseName:
+ 'navigates when left clicking on child element of target="_blank" link',
+ linkAttributes: 'target="_blank"',
+ click: { element: 'a[target="_blank"] > h1' },
+ expected: { requestsOnSamePage: 0, requestsOnOtherPages: 1 }
+ },
+ {
+ caseName:
+ 'does not navigate when left clicking on link that has called event.preventDefault()',
+ linkAttributes: 'onclick="event.preventDefault()"',
+ click: { element: 'a' },
+ expected: { requestsOnSamePage: 0, requestsOnOtherPages: 0 }
+ }
+ ]) {
+ test(`tracks and ${caseName}`, async ({ page, browserName }, {
+ testId
+ }) => {
+ if (skip) {
+ skip(browserName)
+ }
+ const outboundUrl = 'https://other.example.com/target'
+ const outboundMockOptions = {
+ page,
+ path: outboundUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>other page</title></head><body>other page</body></html>'
+ },
+ awaitedRequestCount: 2,
+ mockRequestTimeout: 2000
+ }
+
+ const outboundMockForOtherPages = await mockManyRequests({
+ ...outboundMockOptions,
+ scopeMockToPage: false
+ })
+ const outboundMockForSamePage = await mockManyRequests({
+ ...outboundMockOptions,
+ scopeMockToPage: true
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
+ bodyContent: `<a ${linkAttributes} href="${outboundUrl}"><h1>➡️</h1></a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click(click.element, { modifiers: click.modifiers }),
+ expectedRequests: [
+ { n: 'Outbound Link: Click', p: { url: outboundUrl } }
+ ]
+ })
+
+ const [requestsOnOtherPages, requestsOnSamePage] = await Promise.all([
+ outboundMockForOtherPages.getRequestList().then((d) => d.length),
+ outboundMockForSamePage.getRequestList().then((d) => d.length)
+ ])
+ expect({ requestsOnOtherPages, requestsOnSamePage }).toEqual(expected)
+ })
+ }
+
+ test(`tracking delays navigation until the tracking request has finished`, async ({
+ page
+ }, { testId }) => {
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 1000
+ })
+ const outboundUrl = 'https://other.example.com/target'
+ const outboundMock = await mockManyRequests({
+ page,
+ path: outboundUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>other page</title></head><body>other page</body></html>'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
+ bodyContent: `<a href="${outboundUrl}">📥</a>`
+ })
+ await page.goto(url)
+
+ const navigationPromise = page.waitForRequest(outboundUrl, {
+ timeout: 2000
+ })
+ const trackingPromise = page.waitForResponse('**/api/event', {
+ timeout: 2000
+ })
+
+ await page.click('a')
+ const [[, trackingResponseTime], [, navigationTime]] =
+ await resolveWithTimestamps([trackingPromise, navigationPromise])
+ await expect(page.getByText('other page')).toBeVisible()
+ await expect(outboundMock.getRequestList()).resolves.toHaveLength(1)
+ expect(trackingResponseTime).toBeLessThanOrEqual(navigationTime)
+ await expect(eventsApiMock.getRequestList()).resolves.toEqual([
+ expect.objectContaining({
+ n: 'Outbound Link: Click',
+ p: {
+ url: outboundUrl
+ }
+ })
+ ])
+ })
+
+ test('if the tracking requests delays navigation for more than 5s, it navigates anyway, without waiting for the request to resolve ', async ({
+ page
+ }, { testId }) => {
+ test.setTimeout(20000)
+ await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 6000
+ })
+ const outboundUrl = 'https://other.example.com/target'
+ const outboundMock = await mockManyRequests({
+ page,
+ path: outboundUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>other page</title></head><body>other page</body></html>'
+ },
+ awaitedRequestCount: 1
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.local.manual.outbound-links.js"></script>',
+ bodyContent: `<a href="${outboundUrl}">➡️</a>`
+ })
+ await page.goto(url)
+ const navigationPromise = page.waitForRequest(outboundUrl, {
+ timeout: 6000
+ })
+ await page.click('a')
+ await navigationPromise
+ await expect(page.getByText('other page')).toBeVisible()
+ await expect(outboundMock.getRequestList()).resolves.toHaveLength(1)
+ })
+})
diff --git a/tracker/test/pageview.spec.js b/tracker/test/pageview.spec.js
deleted file mode 100644
index 81fa10c354..0000000000
--- a/tracker/test/pageview.spec.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import { mockRequest, tracker_script_version } from './support/test-utils'
-import { expect, test } from '@playwright/test'
-
-test.describe('Basic installation', () => {
- test('Sends pageview automatically', async ({ page }) => {
- const plausibleRequestMock = mockRequest(page, '/api/event')
- await page.goto('/simple.html')
-
- const plausibleRequest = await plausibleRequestMock
- expect(plausibleRequest.url()).toContain('/api/event')
- expect(plausibleRequest.postDataJSON().n).toEqual('pageview')
- expect(plausibleRequest.postDataJSON().v).toEqual(tracker_script_version)
- })
-})
diff --git a/tracker/test/pageview.spec.ts b/tracker/test/pageview.spec.ts
new file mode 100644
index 0000000000..6ffce6aa2c
--- /dev/null
+++ b/tracker/test/pageview.spec.ts
@@ -0,0 +1,46 @@
+import { initializePageDynamically } from './support/initialize-page-dynamically'
+import {
+ expectPlausibleInAction,
+ isEngagementEvent,
+ switchByMode,
+ tracker_script_version
+} from './support/test-utils'
+import { test } from '@playwright/test'
+import { ScriptConfig } from './support/types'
+import { LOCAL_SERVER_ADDR } from './support/server'
+
+const DEFAULT_CONFIG: ScriptConfig = {
+ domain: 'example.com',
+ endpoint: `${LOCAL_SERVER_ADDR}/api/event`,
+ captureOnLocalhost: true
+}
+
+for (const mode of ['legacy', 'web', 'esm']) {
+ test.describe(`pageviews parity legacy/v2 (${mode})`, () => {
+ test('sends pageview on navigating to page', async ({ page }, {
+ testId
+ }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: DEFAULT_CONFIG,
+ esm: `<script type="module">import { init, track } from '/tracker/js/npm_package/plausible.js'; init(${JSON.stringify(
+ DEFAULT_CONFIG
+ )})</script>`,
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: ''
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.goto(url),
+ expectedRequests: [{ n: 'pageview', v: tracker_script_version }],
+ shouldIgnoreRequest: [isEngagementEvent]
+ })
+ })
+ })
+}
diff --git a/tracker/test/plausible-npm.spec.js b/tracker/test/plausible-npm.spec.js
index ae968dd98a..fb65c61651 100644
--- a/tracker/test/plausible-npm.spec.js
+++ b/tracker/test/plausible-npm.spec.js
@@ -3,14 +3,6 @@ Tests for plausible-npm.js variant
Config is set at init(), as we expect consumers to do in production.
*/
-
-import {
- expectPlausibleInAction,
- hideAndShowCurrentTab,
- metaKey,
- mockRequest,
- e as expecting
-} from './support/test-utils'
import { test, expect } from '@playwright/test'
import { LOCAL_SERVER_ADDR } from './support/server'
import { testPlausibleConfiguration, callInit } from './shared-configuration-tests'
diff --git a/tracker/test/shared-configuration-tests.js b/tracker/test/shared-configuration-tests.js
index 6a7f00a90c..ca94d5c516 100644
--- a/tracker/test/shared-configuration-tests.js
+++ b/tracker/test/shared-configuration-tests.js
@@ -1,8 +1,6 @@
import {
expectPlausibleInAction,
hideAndShowCurrentTab,
- metaKey,
- mockRequest,
e as expecting,
isPageviewEvent,
isEngagementEvent,
@@ -33,9 +31,11 @@ export async function callInit(page, config, parent) {
export function testPlausibleConfiguration({ openPage, initPlausible, fixtureName, fixtureTitle }) {
test.describe('shared configuration tests', () => {
- test.beforeEach(({ page }) => {
+ test.beforeEach(async ({ page }) => {
// Mock file download requests
- mockRequest(page, 'https://awesome.website.com/file.pdf')
+ await page.context().route('https://awesome.website.com/file.pdf', async (request) => {
+ await request.fulfill({status: 200, contentType: 'application/pdf', body: 'mocked pdf content'})
+ })
})
test('triggers pageview and engagement automatically', async ({ page }) => {
@@ -106,7 +106,7 @@ export function testPlausibleConfiguration({ openPage, initPlausible, fixtureNam
await expectPlausibleInAction(page, {
action: async () => {
await openPage(page, {})
- await page.click('#file-download', { modifiers: [metaKey()] })
+ await page.click('#file-download', { modifiers: ['ControlOrMeta'] })
},
expectedRequests: [{ n: 'pageview' } ],
refutedRequests: [{ n: 'File Download' }],
diff --git a/tracker/test/support/dynamic-page-template.html b/tracker/test/support/dynamic-page-template.html
deleted file mode 100644
index ca631abe15..0000000000
--- a/tracker/test/support/dynamic-page-template.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!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>
- // This must be kept in sync with the actual script snippet that customers should use
- (window.plausible =
- window.plausible ||
- function () {
- (window.plausible.q = window.plausible.q || []).push(arguments);
- }),
- (window.plausible.init = function (i) {
- window.plausible.o = i || {};
- });
- var script = document.createElement("script");
- (script.type = "text/javascript"),
- (script.defer = !0),
- (script.src = "<%= plausible_script_url %>");
- var r = document.getElementsByTagName("script")[0];
- r.parentNode.insertBefore(script, r);
- plausible.init();
- </script>
- </head>
-
- <body></body>
-</html>
diff --git a/tracker/test/support/initialize-page-dynamically.ts b/tracker/test/support/initialize-page-dynamically.ts
index 6e5efa5eb5..855a22aafb 100644
--- a/tracker/test/support/initialize-page-dynamically.ts
+++ b/tracker/test/support/initialize-page-dynamically.ts
@@ -1,42 +1,74 @@
-import { Page } from "@playwright/test";
-import { ScriptConfig } from "./types";
-import { readFileSync } from "node:fs";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-const TEMPLATE = readFileSync(
- path.resolve(__dirname, "./dynamic-page-template.html")
-).toString();
+import { Page } from '@playwright/test'
+import { ScriptConfig } from './types'
+import { compileWebSnippet } from '../../compiler'
interface DynamicPageOptions {
- scriptConfig: ScriptConfig;
+ /** string like `<script defer id="plausible" src="/plausible.compat.local.js"></script>` or ScriptConfig to be set to web snippet */
+ scriptConfig: ScriptConfig | string
/** vanilla HTML string, which can contain JS, will be set in the body of the page */
- bodyContent: string;
- testId: string;
+ bodyContent: string
+ testId: string
+ /** optional path to append to the dynamic page URL */
+ path?: string
}
interface DynamicPageInfo {
/** the url where the page is served */
- url: string;
+ url: string
+}
+
+const RESPONSE_BODY_TEMPLATE = `
+<!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>// Plausible script</script>
+ </head>
+ <body></body>
+</html>
+`
+
+const PLAUSIBLE_WEB_SNIPPET = compileWebSnippet()
+
+function getConfiguredPlausibleWebSnippet({
+ autoCapturePageviews,
+ ...injectedScriptConfig
+}: ScriptConfig): string {
+ const snippet = PLAUSIBLE_WEB_SNIPPET.replace(
+ '<%= plausible_script_url %>',
+ `/tracker/js/plausible-web.js?script_config=${encodeURIComponent(
+ JSON.stringify(injectedScriptConfig)
+ )}`
+ )
+ // This option, if provided, must be lifted to script init(overrides) overrides, otherwise it is ignored. It was not meant to be injected.
+ if (autoCapturePageviews !== undefined) {
+ return snippet.replace(
+ 'plausible.init()',
+ `plausible.init({"autoCapturePageviews":${JSON.stringify(autoCapturePageviews)}})`
+ )
+ }
+ return snippet
}
export async function initializePageDynamically(
page: Page,
- { testId, scriptConfig, bodyContent }: DynamicPageOptions
+ { testId, scriptConfig, bodyContent, path = '' }: DynamicPageOptions
): Promise<DynamicPageInfo> {
- const url = `/dynamic/${testId}`;
- await page.route(url, async (route) => {
+ const url = `/dynamic/${testId}${path}`
+ await page.context().route(url, async (route) => {
+ const responseBody = RESPONSE_BODY_TEMPLATE.replace(
+ '<script>// Plausible script</script>',
+ typeof scriptConfig === 'string'
+ ? scriptConfig
+ : getConfiguredPlausibleWebSnippet(scriptConfig)
+ ).replace('<body></body>', `<body>${bodyContent}</body>`)
await route.fulfill({
- body: TEMPLATE.replace(
- "<%= plausible_script_url %>",
- `/tracker/js/plausible-web.js?script_config=${encodeURIComponent(
- JSON.stringify(scriptConfig)
- )}`
- ).replace("<body></body>", `<body>${bodyContent}</body>`),
- contentType: "text/html",
- });
- });
- return { url };
+ body: responseBody,
+ contentType: 'text/html'
+ })
+ })
+ return { url }
}
diff --git a/tracker/test/support/mock-many-requests.ts b/tracker/test/support/mock-many-requests.ts
index f5ea15c4f3..3694b9faea 100644
--- a/tracker/test/support/mock-many-requests.ts
+++ b/tracker/test/support/mock-many-requests.ts
@@ -1,40 +1,71 @@
import { Page } from '@playwright/test'
+import { delay } from './test-utils'
type RequestData = Record<string, unknown>
type ShouldIgnoreRequest = (requestData?: RequestData) => boolean
+const DEFAULT_RESPONSE = { status: 200, contentType: 'text/plain', body: 'ok' }
+
+interface MockManyRequestsOptions {
+ /**
+ * Set `scopeMockToPage` to `true` if there is a need to verify that the mock request
+ * happens on the passed `page`.
+ * Default value is `false`, which means it records requests that open in new tabs as well.
+ * Note: You can create two mocks for the same path, one on the page and other on the browser if needed.
+ */
+ scopeMockToPage?: boolean
+ page: Page
+ path: string
+ /**
+ * Response to fulfill the request with.
+ * Defaults to DEFAULT_RESPONSE. Allows overriding properties from the default one by one.
+ * @see DEFAULT_RESPONSE
+ */
+ fulfill?: {
+ status?: number
+ contentType?: string
+ body?: string
+ }
+ /**
+ * When there's at least `awaitedRequestCount` unignored requests on this route,
+ * getRequestList resolves without waiting for `mockRequestTimeout`.
+ * If there's less than `awaitedRequestCount` unignored requests on this route, it
+ * takes `mockRequestTimeout` to resolve `getRequestList`.
+ * This is so as not miss unexpected requests that are sent slowly.
+ */
+ awaitedRequestCount: number
+ responseDelay?: number
+ shouldIgnoreRequest?: ShouldIgnoreRequest | ShouldIgnoreRequest[]
+ mockRequestTimeout?: number
+}
+
export async function mockManyRequests({
+ scopeMockToPage,
page,
path,
- numberOfRequests,
+ fulfill,
+ awaitedRequestCount,
responseDelay,
shouldIgnoreRequest,
mockRequestTimeout = 3000
-}: {
- page: Page
- path: string
- numberOfRequests: number
- responseDelay?: number
- shouldIgnoreRequest?: ShouldIgnoreRequest | ShouldIgnoreRequest[]
- mockRequestTimeout?: number
-}) {
- const requestList: any[] = []
- await page.route(path, async (route, request) => {
+}: MockManyRequestsOptions) {
+ const requestList: unknown[] = []
+ const scope = scopeMockToPage ? page : page.context()
+ await scope.route(path, async (route, request) => {
+ if (responseDelay) {
+ await delay(responseDelay)
+ }
const postData = request.postDataJSON()
if (shouldAllow(postData, shouldIgnoreRequest)) {
requestList.push(postData)
}
- if (responseDelay) {
- await delay(responseDelay)
- }
await route.fulfill({
- status: 202,
- contentType: 'text/plain',
- body: 'ok'
+ ...DEFAULT_RESPONSE,
+ ...fulfill
})
})
- const getWaitForRequests = () =>
+ const getRequestList = (): Promise<unknown[]> =>
new Promise((resolve) => {
let i = 0
const POLL_INTERVAL_MS = 10
@@ -42,7 +73,7 @@ export async function mockManyRequests({
if (i > mockRequestTimeout / POLL_INTERVAL_MS) {
clearInterval(interval)
resolve(requestList)
- } else if (requestList.length === numberOfRequests) {
+ } else if (requestList.length === awaitedRequestCount) {
clearInterval(interval)
resolve(requestList)
} else {
@@ -51,10 +82,13 @@ export async function mockManyRequests({
}, POLL_INTERVAL_MS)
})
- return getWaitForRequests
+ return { getRequestList }
}
-function shouldAllow(requestData: RequestData, ignores: ShouldIgnoreRequest | ShouldIgnoreRequest[] | undefined) {
+function shouldAllow(
+ requestData: RequestData,
+ ignores: ShouldIgnoreRequest | ShouldIgnoreRequest[] | undefined
+) {
if (Array.isArray(ignores)) {
return !ignores.some((shouldIgnore) => shouldIgnore(requestData))
} else if (ignores) {
@@ -64,6 +98,13 @@ function shouldAllow(requestData: RequestData, ignores: ShouldIgnoreRequest | Sh
}
}
-function delay(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms))
+export function resolveWithTimestamps(
+ promises: Array<Promise<unknown>>
+): Promise<Array<[unknown, number]>> {
+ return Promise.all(
+ promises.map(async (mock) => {
+ const result = await mock
+ return [result, Date.now()]
+ })
+ )
}
diff --git a/tracker/test/support/server.js b/tracker/test/support/server.js
index 27cb477dad..8894b0605c 100644
--- a/tracker/test/support/server.js
+++ b/tracker/test/support/server.js
@@ -20,14 +20,17 @@ export function runLocalFileServer() {
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}`)})
+ } else {
+ let code = await compileFile(variant, { returnCode: true })
- let code = await compileFile(variant, { returnCode: true })
+ if (name === 'plausible-web.js') {
+ code = code.replace('"<%= @config_js %>"', req.query.script_config)
+ }
- if (name === 'plausible-web.js') {
- code = code.replace('"<%= @config_js %>"', req.query.script_config)
- }
-
- res.type('application/javascript').send(code)
+ res.type('application/javascript').send(code)
+ }
});
// A test utility - serve an image with an artificial delay
diff --git a/tracker/test/support/test-utils.js b/tracker/test/support/test-utils.js
index 6dfe747d65..f11253278a 100644
--- a/tracker/test/support/test-utils.js
+++ b/tracker/test/support/test-utils.js
@@ -4,28 +4,6 @@ import { mockManyRequests } from "./mock-many-requests"
export const tracker_script_version = packageJson.tracker_script_version
-// Mocks an HTTP request call with the given path. Returns a Promise that resolves to the request
-// data. If the request is not made, resolves to null after 3 seconds.
-export const mockRequest = function (page, path) {
- return new Promise((resolve, _reject) => {
- const requestTimeoutTimer = setTimeout(() => resolve(null), 3000)
-
- page.route(path, (route, request) => {
- clearTimeout(requestTimeoutTimer)
- resolve(request)
- return route.fulfill({ status: 202, contentType: 'text/plain', body: 'ok' })
- })
- })
-}
-
-export const metaKey = function() {
- if (process.platform === 'darwin') {
- return 'Meta'
- } else {
- return 'Control'
- }
-}
-
/**
* A powerful utility function that makes it easy to assert on the event
* requests that should or should not have been made after doing a page
@@ -52,7 +30,7 @@ export const metaKey = function() {
* @param {Array|Function} [args.shouldIgnoreRequest] - When provided, ignores certain requests
* @param {number} [args.responseDelay] - When provided, delays the response from the Plausible
* API by the given number of milliseconds.
- * @param {Function} [args.mockRequestTimeout] - How long to wait for the requests to be made
+ * @param {number} [args.mockRequestTimeout] - How long to wait for the requests to be made
*/
export const expectPlausibleInAction = async function (page, {
action,
@@ -68,13 +46,14 @@ export const expectPlausibleInAction = async function (page, {
const requestsToExpect = expectedRequestCount ? expectedRequestCount : expectedRequests.length
const requestsToAwait = awaitedRequestCount ? awaitedRequestCount : requestsToExpect + refutedRequests.length
- const getRequestList = await mockManyRequests({
+ const { getRequestList } = await mockManyRequests({
page,
path: pathToMock,
+ fulfill: { status: 202, contentType: 'text/plain', body: 'ok' },
responseDelay,
shouldIgnoreRequest,
- numberOfRequests: requestsToAwait,
- mockRequestTimeout: mockRequestTimeout
+ awaitedRequestCount: requestsToAwait,
+ mockRequestTimeout
})
await action()
const requestBodies = await getRequestList()
@@ -211,3 +190,16 @@ function checkEqual(a, b) {
export function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
+
+export function switchByMode(cases, mode) {
+ switch (mode) {
+ case 'web':
+ return cases.web
+ case 'esm':
+ return cases.esm
+ case 'legacy':
+ return cases.legacy
+ default:
+ throw new Error(`Unimplemented mode: ${mode}`)
+ }
+}
\ No newline at end of file
diff --git a/tracker/test/support/types.ts b/tracker/test/support/types.ts
index ffaa2f8b00..e7a29f0504 100644
--- a/tracker/test/support/types.ts
+++ b/tracker/test/support/types.ts
@@ -1,13 +1,13 @@
export type Options = {
- hashBasedRouting: boolean;
- outboundLinks: boolean;
- fileDownloads: boolean;
- formSubmissions: boolean;
- captureOnLocalhost: boolean;
- autoCapturePageviews: boolean;
-};
+ hashBasedRouting: boolean
+ outboundLinks: boolean
+ fileDownloads: boolean | string[]
+ formSubmissions: boolean
+ captureOnLocalhost: boolean
+ autoCapturePageviews: boolean
+}
export type ScriptConfig = {
- domain: string;
- endpoint: string;
-} & Partial<Options>;
+ domain: string
+ endpoint: string
+} & Partial<Options>
diff --git a/tracker/test/tagged-events.spec.js b/tracker/test/tagged-events.spec.js
deleted file mode 100644
index 02d0c54395..0000000000
--- a/tracker/test/tagged-events.spec.js
+++ /dev/null
@@ -1,121 +0,0 @@
-import { mockRequest, metaKey, expectPlausibleInAction } from './support/test-utils'
-import { expect, test } from '@playwright/test'
-
-test.describe('tagged-events extension', () => {
- test('tracks a tagged link click with custom props + url prop', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- const linkURL = await page.locator('#link').getAttribute('href')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link'),
- expectedRequests: [{n: 'Payment Complete', p: {amount: '100', method: "Credit Card", url: linkURL}}]
- })
- })
-
- test('tracks a tagged form submit with custom props when submitting by pressing enter', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- const submitForm = async function() {
- const inputLocator = page.locator('#form-text-input')
- await inputLocator.fill('some input')
- await inputLocator.press('Enter')
- }
-
- await expectPlausibleInAction(page, {
- action: submitForm,
- expectedRequests: [{n: 'Signup', p: {type: "Newsletter"}}]
- })
- })
-
- test('tracks submit on a form with a tagged parent when submit button is clicked', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#submit-form-with-tagged-parent'),
- expectedRequests: [{n: 'Form Submit', p: {}}],
- awaitedRequestCount: 2,
- expectedRequestCount: 1
- })
- })
-
- test('tracks click and auxclick on any tagged HTML element', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- const expectedRequests = [{n: 'Custom Event', p: { foo: "bar" }}]
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#button'),
- expectedRequests
- })
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#span'),
- expectedRequests
- })
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#div', { modifiers: [metaKey()] }),
- expectedRequests
- })
- })
-
- test('does not track elements without plausible-event-name class + link elements navigate', async ({ page }) => {
- await page.goto('/tagged-event.html')
- const linkLocator = page.locator('#not-tracked-link')
-
- const linkURL = await linkLocator.getAttribute('href')
-
- const plausibleRequestMock = mockRequest(page, '/api/event')
- const navigationRequestMock = mockRequest(page, linkURL)
-
- await page.click('#not-tracked-button')
- await page.click('#not-tracked-span')
- await linkLocator.click()
-
- expect(await plausibleRequestMock, "should not have made Plausible request").toBeNull()
- expect((await navigationRequestMock).url()).toContain(linkURL)
- })
-
- test('tracks tagged HTML elements when their child element is clicked', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- const expectedRequests = [
- {n: 'Custom Event', p: { foo: "bar", url: "https://awesome.website.com/payment/"}}
- ]
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#h2-with-link-parent', { modifiers: [metaKey()] }),
- expectedRequests
- })
-
- await expectPlausibleInAction(page, {
- action: () => page.click('#link-with-div-parent'),
- expectedRequests
- })
- })
-
- test('tracks tagged element that is dynamically added to the DOM', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- const buttonLocator = page.locator('#dynamic-tagged-button')
- await buttonLocator.waitFor({state: 'visible'})
-
- await expectPlausibleInAction(page, {
- action: () => buttonLocator.click(),
- expectedRequests: [{n: 'Custom Event', p: {}}]
- })
- })
-
- test('does not track clicks inside a tagged form, except submit click', async ({ page }) => {
- await page.goto('/tagged-event.html')
-
- const plausibleRequestMock = mockRequest(page, '/api/event')
-
- await page.click('#form')
- await page.click('#form-input')
- await page.click('#form-div')
-
- expect(await plausibleRequestMock, "should not have made Plausible request").toBeNull()
- })
-})
diff --git a/tracker/test/tagged-events.spec.ts b/tracker/test/tagged-events.spec.ts
new file mode 100644
index 0000000000..bda9a35ac1
--- /dev/null
+++ b/tracker/test/tagged-events.spec.ts
@@ -0,0 +1,597 @@
+import {
+ expectPlausibleInAction,
+ isPageviewEvent,
+ isEngagementEvent,
+ switchByMode
+} from './support/test-utils'
+import { expect, test } from '@playwright/test'
+import { LOCAL_SERVER_ADDR } from './support/server'
+import { initializePageDynamically } from './support/initialize-page-dynamically'
+import { ScriptConfig } from './support/types'
+import {
+ mockManyRequests,
+ resolveWithTimestamps
+} from './support/mock-many-requests'
+
+const DEFAULT_CONFIG: ScriptConfig = {
+ domain: 'example.com',
+ endpoint: `${LOCAL_SERVER_ADDR}/api/event`,
+ captureOnLocalhost: true
+}
+
+test.beforeEach(async ({ page }) => {
+ await page
+ .context()
+ .route(new RegExp('(http|https)://example\\.com.*'), async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>mocked page</title></head><body>mocked page</body></html>'
+ })
+ })
+})
+
+for (const mode of ['legacy', 'web']) {
+ test.describe(`tagged events feature legacy/v2 parity (${mode})`, () => {
+ test('tracks link click and child of link click when link is tagged (using plausible-event-... double dash syntax)', async ({
+ page
+ }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ 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>
+ </a>`
+ })
+ await page.goto(url)
+
+ const expectedRequests = [
+ {
+ n: 'Payment Complete',
+ p: {
+ amount: '100',
+ method: 'Credit Card',
+ url: 'https://example.com/payment?secret=foo'
+ }
+ }
+ ]
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a', { modifiers: ['ControlOrMeta'] }), // open in new tab
+ expectedRequests,
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('h1'),
+ expectedRequests,
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks link press when its parent div is tagged (using plausible-event-... equals syntax)', async ({
+ page
+ }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<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)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.press('a', 'Enter'),
+ expectedRequests: [
+ {
+ n: 'Reset Password',
+ p: {
+ foo: 'bar',
+ url: 'https://example.com/reset?verification=123'
+ }
+ }
+ ],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks tagged form submitted using Enter in text input', async ({
+ page
+ }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `
+ <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" />
+ <input type="submit" value="Submit" />
+ </form>`
+ })
+ await page.goto(url)
+
+ // if the form is tagged, clicks within the form should not trigger events
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await page.click('form')
+ await page.click('h2')
+ await page.click('label', { button: 'right' })
+ },
+ expectedRequests: [],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await page.fill('input[type="email"]', '[email protected]')
+ await page.press('input[type="email"]', 'Enter')
+ },
+ expectedRequests: [
+ {
+ n: 'Signup',
+ p: { type: 'Newsletter' }
+ }
+ ],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks only submit in a form when its parent is tagged', async ({
+ page
+ }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `
+ <div class="plausible-event-name=Form+Submit">
+ <form action="https://example.com/register" method="post">
+ <input type="text"/>
+ <input type="submit" value="Submit" />
+ </form>
+ </div>`
+ })
+ await page.goto(url)
+
+ // if the form parent is tagged, clicks within the form should not trigger events
+ await expectPlausibleInAction(page, {
+ action: async () => {
+ await page.click('form')
+ await page.click('input[type="text"]')
+ },
+ expectedRequests: [],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('input[type="submit"]'),
+ expectedRequests: [
+ {
+ n: 'Form Submit'
+ }
+ ],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks tagged span click and clicks on any child', async ({ page }, {
+ testId
+ }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<span class="plausible-event-name=Custom+Event plausible-event-foo=bar"><strong>any</strong>text</span>`
+ })
+ await page.goto(url)
+
+ const expectedRequests = [
+ {
+ n: 'Custom Event',
+ p: { foo: 'bar' }
+ }
+ ]
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('span'),
+ expectedRequests,
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('strong'),
+ expectedRequests,
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks tagged button click', async ({ page }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<button class="plausible-event-name=Custom+Event plausible-event-foo=bar">✅</button>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('button'),
+ expectedRequests: [
+ {
+ n: 'Custom Event',
+ p: { foo: 'bar' }
+ }
+ ],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks dynamically added tagged button', async ({ page }, {
+ testId
+ }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: ''
+ })
+ await page.goto(url)
+
+ await page.evaluate(() => {
+ return new Promise((resolve) => {
+ let taggedElement
+ while (!taggedElement) {
+ if ((window as any).plausible?.l !== true) {
+ continue
+ } else {
+ taggedElement = document.createElement('button')
+ taggedElement.classList.add('plausible-event-name=Custom+Event')
+ taggedElement.innerHTML += 'Dynamic'
+ document.body.appendChild(taggedElement)
+ }
+ }
+ resolve(true)
+ })
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('button'),
+ expectedRequests: [
+ {
+ n: 'Custom Event'
+ }
+ ],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('tracks tagged links without delaying navigation, relying on fetch options.keepalive to deliver tracking events', async ({
+ page
+ }, { testId }) => {
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 500
+ })
+ const targetPage = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: '',
+ bodyContent: `<h1>Subscription successful</h1>`,
+ path: '/target'
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG, autoCapturePageviews: false },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.manual.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<a class="plausible-event-name=Subscribe" href="${targetPage.url}">Click to subscribe</a>`
+ })
+ await page.goto(url)
+ const navigationPromise = page.waitForRequest(targetPage.url, {
+ timeout: 2000
+ })
+ await page.click('a')
+ const [[trackingRequestList, trackingResponseTime], [, navigationTime]] =
+ await resolveWithTimestamps([
+ eventsApiMock.getRequestList(),
+ navigationPromise
+ ])
+ await expect(page.getByText('Subscription successful')).toBeVisible()
+ expect(navigationTime).toBeLessThanOrEqual(trackingResponseTime)
+ expect(trackingRequestList).toEqual([
+ expect.objectContaining({
+ n: 'Subscribe',
+ p: {
+ url: `${LOCAL_SERVER_ADDR}${targetPage.url}`
+ }
+ })
+ ])
+ })
+
+ test('does not track button without plausible-event-name class', async ({
+ page
+ }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<button class="anything">✅</button>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('button'),
+ refutedRequests: [{ n: expect.any(String) }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+
+ test('does not track click on span with class="plausible-event-name="', async ({
+ page
+ }, { testId }) => {
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: switchByMode(
+ {
+ web: { ...DEFAULT_CONFIG },
+ legacy:
+ '<script defer src="/tracker/js/plausible.local.tagged-events.js"></script>'
+ },
+ mode
+ ),
+ bodyContent: `<span class="plausible-event-name=">anything</span>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('span'),
+ refutedRequests: [{ n: expect.any(String) }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+ })
+ })
+}
+
+test.describe('tagged events feature when using legacy .compat extension', () => {
+ for (const { caseName, linkAttributes, click, expected, skip } of [
+ {
+ caseName: 'navigates when left clicking on tagged link',
+ linkAttributes: '',
+ click: { element: 'a' },
+ expected: { requestsOnSamePage: 1, requestsOnOtherPages: 0 }
+ },
+ {
+ caseName:
+ 'navigates when left clicking on tagged link with Ctrl or Meta key',
+ linkAttributes: '',
+ click: { element: 'a', modifiers: ['ControlOrMeta' as const] },
+ expected: { requestsOnSamePage: 0, requestsOnOtherPages: 1 },
+ skip: (browserName) =>
+ test.skip(
+ browserName === 'webkit',
+ 'does not open links with such clicks (works when testing manually in macOS Safari)'
+ )
+ },
+ {
+ caseName:
+ 'navigates when left clicking on child element of target="_blank" tagged link',
+ linkAttributes: 'target="_blank"',
+ click: { element: 'a[target="_blank"] > h1' },
+ expected: { requestsOnSamePage: 0, requestsOnOtherPages: 1 }
+ },
+ {
+ caseName:
+ 'does not navigate when left clicking on tagged link that has called event.preventDefault()',
+ linkAttributes: 'onclick="event.preventDefault()"',
+ click: { element: 'a' },
+ expected: { requestsOnSamePage: 0, requestsOnOtherPages: 0 }
+ }
+ ]) {
+ test(`tracks and ${caseName}`, async ({ page, browserName }, {
+ testId
+ }) => {
+ if (skip) {
+ skip(browserName)
+ }
+ const outboundUrl = 'https://other.example.com/target'
+ const outboundMockOptions = {
+ page,
+ path: outboundUrl,
+ fulfill: {
+ status: 200,
+ contentType: 'text/html',
+ body: '<!DOCTYPE html><html><head><title>other page</title></head><body>other page</body></html>'
+ },
+ awaitedRequestCount: 2,
+ mockRequestTimeout: 2000
+ }
+
+ const outboundMockForOtherPages = await mockManyRequests({
+ ...outboundMockOptions,
+ scopeMockToPage: false
+ })
+ const outboundMockForSamePage = await mockManyRequests({
+ ...outboundMockOptions,
+ scopeMockToPage: true
+ })
+
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer src="/tracker/js/plausible.compat.local.manual.tagged-events.js"></script>',
+ bodyContent: `<a class="plausible-event-name=outbound" ${linkAttributes} href="${outboundUrl}"><h1>➡️</h1></a>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click(click.element, { modifiers: click.modifiers }),
+ expectedRequests: [{ n: 'outbound', p: { url: outboundUrl } }]
+ })
+
+ const [requestsOnOtherPages, requestsOnSamePage] = await Promise.all([
+ outboundMockForOtherPages.getRequestList().then((d) => d.length),
+ outboundMockForSamePage.getRequestList().then((d) => d.length)
+ ])
+ expect({ requestsOnOtherPages, requestsOnSamePage }).toEqual(expected)
+ })
+ }
+
+ test('tracking delays navigation until the tracking request has finished', async ({
+ page
+ }, { testId }) => {
+ const eventsApiMock = await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 1000
+ })
+ const targetPage = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: '',
+ bodyContent: `<h1>Subscription successful</h1>`,
+ path: '/target'
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer 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>`
+ })
+ await page.goto(url)
+ const navigationPromise = page.waitForRequest(targetPage.url, {
+ timeout: 2000
+ })
+ const trackingPromise = page.waitForResponse('**/api/event', {
+ timeout: 2000
+ })
+ await page.click('a')
+ const [[, trackingResponseTime], [, navigationTime]] =
+ await resolveWithTimestamps([trackingPromise, navigationPromise])
+ await expect(page.getByText('Subscription successful')).toBeVisible()
+ expect(trackingResponseTime).toBeLessThan(navigationTime)
+ await expect(eventsApiMock.getRequestList()).resolves.toEqual([
+ expect.objectContaining({
+ n: 'Subscribe',
+ p: {
+ url: `${LOCAL_SERVER_ADDR}${targetPage.url}`
+ }
+ })
+ ])
+ })
+
+ test('if the tracking requests delays navigation for more than 5s, it navigates anyway, without waiting for the request to resolve', async ({
+ page
+ }, { testId }) => {
+ test.setTimeout(20000)
+ await mockManyRequests({
+ page,
+ path: '**/api/event',
+ awaitedRequestCount: 1,
+ responseDelay: 6000
+ })
+ const targetPage = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: '',
+ bodyContent: `<h1>Subscription successful</h1>`,
+ path: '/target'
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer 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>`
+ })
+ await page.goto(url)
+ const navigationPromise = page.waitForRequest(targetPage.url, {
+ timeout: 6000
+ })
+ await page.click('a')
+ await navigationPromise
+ await expect(page.getByText('Subscription successful')).toBeVisible()
+ })
+
+ test('does not track link without plausible-event-name class, the link still navigates as it should', async ({
+ page
+ }, { testId }) => {
+ const targetPage = await initializePageDynamically(page, {
+ testId,
+ scriptConfig: '',
+ bodyContent: `<h1>Subscription successful</h1>`,
+ path: '/target'
+ })
+ const { url } = await initializePageDynamically(page, {
+ testId,
+ scriptConfig:
+ '<script id="plausible" defer 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>`
+ })
+ await page.goto(url)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('a'),
+ refutedRequests: [{ n: expect.any(String) }],
+ shouldIgnoreRequest: [isPageviewEvent, isEngagementEvent]
+ })
+
+ await expect(page.getByText('Subscription successful')).toBeVisible()
+ })
+})