Skip to content

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

Avoid compiling pageleave variant and p.js (#5351)

Karl-Aksel Puulmanna3db3af806f0
diff --git a/.gitignore b/.gitignore
index 2e11afb908..196e5af652 100644
--- a/.gitignore
+++ b/.gitignore
@@ -84,7 +84,7 @@ plausible-report.xml
/priv/geodb/*.mmdb.gz
# Auto-generated tracker files
-/priv/tracker/js/*.js
+/priv/tracker/js/plausible*.js
# Docker volumes
.clickhouse_db_vol*
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c89d87c62..2c3e316aab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,8 @@ All notable changes to this project will be documented in this file.
### Removed
+- `pageleave` tracker script variant is no longer compiled but is still available from /js endpoint.
+
### Changed
- A session is now marked as a bounce if it has less than 2 pageviews and no interactive custom events.
diff --git a/lib/plausible_web/plugs/tracker.ex b/lib/plausible_web/plugs/tracker.ex
index 5b7387e65a..64a81aa9fa 100644
--- a/lib/plausible_web/plugs/tracker.ex
+++ b/lib/plausible_web/plugs/tracker.ex
@@ -61,12 +61,15 @@ defmodule PlausibleWeb.Tracker do
end
end
+ # Variants which do not factor into output
+ @ignore_variants ["js", "pageleave"]
+
defp sorted_script_variant(requested_filename) do
case String.split(requested_filename, ".") do
[base_filename | rest] when base_filename in @base_filenames ->
sorted_variants =
rest
- |> List.delete("js")
+ |> Enum.reject(&(&1 in @ignore_variants))
|> Enum.sort()
Enum.join(["plausible"] ++ sorted_variants ++ ["js"], ".")
diff --git a/priv/tracker/js/p.js b/priv/tracker/js/p.js
new file mode 100644
index 0000000000..f9ebf6234b
--- /dev/null
+++ b/priv/tracker/js/p.js
@@ -0,0 +1 @@
+!function(){var e=window.document.currentScript,r=new URL(e.src).origin;function o(e){console.warn("[Plausible] Ignoring event because "+e)}function a(){var e,i,n,t=JSON.parse((t="plausible_user",(t=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)")))?decodeURIComponent(t[1]):null));return t?{initial_referrer:t.initial_referrer&&decodeURIComponent(t.initial_referrer),initial_source:t.initial_source&&decodeURIComponent(t.initial_source)}:(t={initial_referrer:window.document.referrer||null,initial_source:getSourceFromQueryParam()},e="plausible_user",i=JSON.stringify({initial_referrer:t.initial_referrer&&encodeURIComponent(t.initial_referrer),initial_source:t.initial_source&&encodeURIComponent(t.initial_source)}),(n=new Date).setTime(n.getTime()+94608e6),n="; expires="+n.toUTCString(),document.cookie=e+"="+(i||"")+n+"; samesite=strict; path=/",t)}function i(e,i){var n,t;return/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(window.location.hostname)||"file:"===window.location.protocol?o("website is running locally"):"prerender"===window.document.visibilityState?o("document is prerendering"):((n=c.trackAcquisition?a():{}).n=e,n.u=window.location.href,n.d=c.domain,n.r=window.document.referrer||null,n.w=window.innerWidth,(t=new XMLHttpRequest).open("POST",r+"/api/event",!0),t.setRequestHeader("Content-Type","text/plain"),t.send(JSON.stringify(n)),void(t.onreadystatechange=function(){t.readyState==XMLHttpRequest.DONE&&i&&i.callback&&i.callback()}))}function n(e){i("pageview",e)}try{var c={domain:window.location.hostname},t={page:n,trigger:i,trackPushState:function(){var e,i=window.history;i.pushState&&(e=i.pushState,i.pushState=function(){e.apply(this,arguments),n()}),window.addEventListener("popstate",n)},configure:function(e,i){c[e]=i}},l=window.plausible.q||[];window.plausible=function(){var e=[].slice.call(arguments),i=e.shift();t[i].apply(this,e)};for(var s=0;s<l.length;s++)window.plausible.apply(this,l[s])}catch(e){(new Image).src=r+"/api/error?message="+encodeURIComponent(e.message)}}();
\ No newline at end of file
diff --git a/tracker/compile.js b/tracker/compile.js
index 8d1548dc92..7afd225a25 100644
--- a/tracker/compile.js
+++ b/tracker/compile.js
@@ -33,11 +33,10 @@ function compilefile(input, output, templateVars = {}) {
}
}
-const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue", "pageleave"]
+const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue"]
const variants = [...g.clone.powerSet(base_variants)].filter(a => a.length > 0).map(a => a.sort());
compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.js'))
-compilefile(relPath('src/p.js'), relPath('../priv/tracker/js/p.js'))
variants.map(variant => {
const options = variant.map(variant => variant.replace('-', '_')).reduce((acc, curr) => (acc[curr] = true, acc), {})
diff --git a/tracker/package.json b/tracker/package.json
index 9145a69742..1d8d65345a 100644
--- a/tracker/package.json
+++ b/tracker/package.json
@@ -1,5 +1,5 @@
{
- "tracker_script_version": 5,
+ "tracker_script_version": 6,
"scripts": {
"deploy": "node compile.js",
"test": "npm run deploy && npx playwright test",
diff --git a/tracker/src/p.js b/tracker/src/p.js
deleted file mode 100644
index 501a40f3fe..0000000000
--- a/tracker/src/p.js
+++ /dev/null
@@ -1,123 +0,0 @@
-// NOTE: This file is deprecated and only kept around so we don't break compatibility
-// with some early customers. This script uses a cookie but this was an old version of Plausible.
-// Current script can be found in the tracker/src/plausible.js file
-
-(function(){
- 'use strict';
-
- var scriptEl = window.document.currentScript;
- var plausibleHost = new URL(scriptEl.src).origin
-
- function setCookie(name,value) {
- var date = new Date();
- date.setTime(date.getTime() + (3*365*24*60*60*1000)); // 3 YEARS
- var expires = "; expires=" + date.toUTCString();
- document.cookie = name + "=" + (value || "") + expires + "; samesite=strict; path=/";
- }
-
- function getCookie(name) {
- var matches = document.cookie.match(new RegExp(
- "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
- ));
- return matches ? decodeURIComponent(matches[1]) : null;
- }
-
- function ignore(reason) {
- console.warn('[Plausible] Ignoring event because ' + reason);
- }
-
- function getUserData() {
- var userData = JSON.parse(getCookie('plausible_user'))
-
- if (userData) {
- return {
- initial_referrer: userData.initial_referrer && decodeURIComponent(userData.initial_referrer),
- initial_source: userData.initial_source && decodeURIComponent(userData.initial_source)
- }
- } else {
- userData = {
- initial_referrer: window.document.referrer || null,
- initial_source: getSourceFromQueryParam(),
- }
-
- setCookie('plausible_user', JSON.stringify({
- initial_referrer: userData.initial_referrer && encodeURIComponent(userData.initial_referrer),
- initial_source: userData.initial_source && encodeURIComponent(userData.initial_source),
- }))
-
- return userData
- }
- }
-
- function trigger(eventName, options) {
- if (/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(window.location.hostname)) return ignore('website is running locally');
- if (window.location.protocol === 'file:') return ignore('website is running locally');
- if (window.document.visibilityState === 'prerender') return ignore('document is prerendering');
-
- var payload = CONFIG['trackAcquisition'] ? getUserData() : {}
- payload.n = eventName
- payload.u = window.location.href
- payload.d = CONFIG['domain']
- payload.r = window.document.referrer || null
- payload.w = window.innerWidth
-
- var request = new XMLHttpRequest();
- request.open('POST', plausibleHost + '/api/event', true);
- request.setRequestHeader('Content-Type', 'text/plain');
-
- request.send(JSON.stringify(payload));
-
- request.onreadystatechange = function() {
- if (request.readyState == XMLHttpRequest.DONE) {
- options && options.callback && options.callback()
- }
- }
- }
-
- function page(options) {
- trigger('pageview', options)
- }
-
- function trackPushState() {
- var his = window.history
- if (his.pushState) {
- var originalFn = his['pushState']
- his.pushState = function() {
- originalFn.apply(this, arguments)
- page();
- }
- }
- window.addEventListener('popstate', page)
- }
-
- function configure(key, val) {
- CONFIG[key] = val
- }
-
- try {
- var CONFIG = {
- domain: window.location.hostname
- }
-
- var functions = {
- page: page,
- trigger: trigger,
- trackPushState: trackPushState,
- configure: configure
- }
-
- var queue = window.plausible.q || []
-
- window.plausible = function() {
- var args = [].slice.call(arguments);
- var funcName = args.shift();
- functions[funcName].apply(this, args);
- };
-
- for (var i = 0; i < queue.length; i++) {
- window.plausible.apply(this, queue[i])
- }
- } catch (e) {
- new Image().src = plausibleHost + '/api/error?message=' + encodeURIComponent(e.message);
- }
-})();
diff --git a/tracker/test/engagement.spec.js b/tracker/test/engagement.spec.js
index 615be22cf1..ec91ffa2e4 100644
--- a/tracker/test/engagement.spec.js
+++ b/tracker/test/engagement.spec.js
@@ -105,7 +105,7 @@ test.describe('engagement events', () => {
})
})
- test('script.exclusions.hash.pageleave.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, {