Skip to content

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

Add unload event to the tracking script

Uku Tahtddac5685a24a
diff --git a/assets/js/p.js b/assets/js/p.js
index 15d14553ad..c0133ad34c 100644
--- a/assets/js/p.js
+++ b/assets/js/p.js
@@ -101,8 +101,14 @@
}
+ function onUnload() {
+ var userData = getUserData()
+ navigator.sendBeacon(plausibleHost + '/api/unload', JSON.stringify({uid: userData.uid}));
+ }
+
function page(options) {
trigger('pageview', options)
+ window.addEventListener('unload', onUnload, false);
}
function trackPushState() {
diff --git a/assets/js/plausible.js b/assets/js/plausible.js
index b23a3e3d6a..af9971cf07 100644
--- a/assets/js/plausible.js
+++ b/assets/js/plausible.js
@@ -100,8 +100,14 @@
}
+ function onUnload() {
+ var userData = getUserData()
+ navigator.sendBeacon(plausibleHost + '/api/unload', JSON.stringify({uid: userData.uid}));
+ }
+
function page() {
trigger('pageview')
+ window.addEventListener('unload', onUnload, false);
}
var his = window.history
diff --git a/lib/plausible_web/controllers/api/external_controller.ex b/lib/plausible_web/controllers/api/external_controller.ex
index 1f46733fcc..7b3322b180 100644
--- a/lib/plausible_web/controllers/api/external_controller.ex
+++ b/lib/plausible_web/controllers/api/external_controller.ex
@@ -19,6 +19,12 @@ defmodule PlausibleWeb.Api.ExternalController do
end
end
+ def unload(conn, _params) do
+ params = parse_body(conn)
+ Plausible.Ingest.Session.on_unload(params["uid"], Timex.now())
+ conn |> send_resp(202, "")
+ end
+
def error(conn, _params) do
request = Sentry.Plug.build_request_interface_data(conn, [])
Sentry.capture_message("JS snippet error", request: request)
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index 60a2157d34..d3372e2590 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -50,6 +50,7 @@ defmodule PlausibleWeb.Router do
pipe_through :api
post "/event", Api.ExternalController, :event
+ post "/unload", Api.ExternalController, :unload
get "/error", Api.ExternalController, :error
post "/paddle/webhook", Api.PaddleController, :webhook