Skip to content

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

Add tracker feature to automatically track outbound links (#389)

Uku Tahtf0cbf33d7c39
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93a155e270..76778b7b9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file.
### Added
- Ability to add event metadata plausible/analytics#381
+- Add tracker module to automatically track outbound links plausible/analytics#389
- Display weekday on the visitor graph plausible/analytics#175
### Changed
diff --git a/lib/plausible_web/controllers/tracker_controller.ex b/lib/plausible_web/controllers/tracker_controller.ex
deleted file mode 100644
index 08cbed5633..0000000000
--- a/lib/plausible_web/controllers/tracker_controller.ex
+++ /dev/null
@@ -1,55 +0,0 @@
-defmodule PlausibleWeb.TrackerController do
- use PlausibleWeb, :controller
- require EEx
-
- EEx.function_from_file(
- :defp,
- :render_plausible,
- Application.app_dir(:plausible, "priv/tracker/js/plausible.js"),
- [:base_url]
- )
-
- EEx.function_from_file(
- :defp,
- :render_plausible_hash,
- Application.app_dir(:plausible, "priv/tracker/js/plausible.hash.js"),
- [:base_url]
- )
-
- EEx.function_from_file(
- :defp,
- :render_p,
- Application.app_dir(:plausible, "priv/tracker/js/p.js"),
- [:base_url]
- )
-
- #  1 hour
- @max_age 3600
-
- def plausible(conn, _params) do
- send_js(conn, render_plausible(base_url()))
- end
-
- def plausible_hash(conn, _params) do
- send_js(conn, render_plausible_hash(base_url()))
- end
-
- def analytics(conn, _params) do
- send_js(conn, render_plausible(base_url()))
- end
-
- def p(conn, _params) do
- send_js(conn, render_p(base_url()))
- end
-
- defp send_js(conn, file) do
- conn
- |> put_resp_header("cache-control", "max-age=#{@max_age},public")
- |> put_resp_header("content-type", "application/javascript")
- |> send_resp(200, file)
- end
-
- defp base_url() do
- PlausibleWeb.Endpoint.url()
- end
-end
diff --git a/lib/plausible_web/endpoint.ex b/lib/plausible_web/endpoint.ex
index 9a9b85e103..230472d43f 100644
--- a/lib/plausible_web/endpoint.ex
+++ b/lib/plausible_web/endpoint.ex
@@ -40,5 +40,6 @@ defmodule PlausibleWeb.Endpoint do
extra: "SameSite=Lax"
plug CORSPlug
+ plug PlausibleWeb.Tracker
plug PlausibleWeb.Router
end
diff --git a/lib/plausible_web/plugs/tracker.ex b/lib/plausible_web/plugs/tracker.ex
new file mode 100644
index 0000000000..ecf0e78123
--- /dev/null
+++ b/lib/plausible_web/plugs/tracker.ex
@@ -0,0 +1,45 @@
+defmodule PlausibleWeb.Tracker do
+ import Plug.Conn
+ @templates [
+ "plausible.js",
+ "plausible.hash.js",
+ "plausible.hash.outbound-links.js",
+ "plausible.outbound-links.js",
+ "p.js"
+ ]
+ @aliases %{
+ "plausible.js" => ["analytics.js"],
+ "plausible.hash.outbound-links.js" => ["plausible.outbound-links.hash.js"]
+ }
+
+ #  1 hour
+ @max_age 3600
+
+ def init(_) do
+ templates = Enum.reduce(@templates, %{}, fn template_filename, rendered_templates ->
+ rendered = EEx.eval_file("priv/tracker/js/" <> template_filename, base_url: PlausibleWeb.Endpoint.url())
+ aliases = Map.get(@aliases, template_filename, [])
+ [template_filename | aliases]
+ |> Enum.map(fn filename -> {"/js/" <> filename, rendered} end)
+ |> Enum.into(%{})
+ |> Map.merge(rendered_templates)
+ end)
+
+ [templates: templates]
+ end
+
+ def call(conn, templates: templates) do
+ case templates[conn.request_path] do
+ found when is_binary(found) -> send_js(conn, found)
+ nil -> conn
+ end
+ end
+
+ defp send_js(conn, file) do
+ conn
+ |> put_resp_header("cache-control", "max-age=#{@max_age},public")
+ |> put_resp_header("content-type", "application/javascript")
+ |> send_resp(200, file)
+ |> halt()
+ end
+end
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index d59fb545eb..322c5c24c9 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -36,11 +36,6 @@ defmodule PlausibleWeb.Router do
forward "/sent-emails", Bamboo.SentEmailViewerPlug
end
- get "/js/plausible.js", PlausibleWeb.TrackerController, :plausible
- get "/js/plausible.hash.js", PlausibleWeb.TrackerController, :plausible_hash
- get "/js/analytics.js", PlausibleWeb.TrackerController, :plausible
- get "/js/p.js", PlausibleWeb.TrackerController, :p
-
scope "/api/stats", PlausibleWeb.Api do
pipe_through :stats_api
diff --git a/priv/tracker/js/plausible.hash.outbound-links.js b/priv/tracker/js/plausible.hash.outbound-links.js
new file mode 100644
index 0000000000..f7b891f7b3
--- /dev/null
+++ b/priv/tracker/js/plausible.hash.outbound-links.js
@@ -0,0 +1 @@
+!function(r,i){"use strict";var o=r.location,s=r.document,e=s.querySelector('[src*="'+i+'"]'),l=e&&e.getAttribute("data-domain"),t=!1;function a(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(o.hostname)||"file:"===o.protocol)return console.warn("Ignoring event on localhost");var a={};a.n=e,a.u=o.href,a.d=l,a.r=s.referrer||null,a.w=r.innerWidth,t&&t.meta&&(a.m=JSON.stringify(t.meta)),t&&t.props&&(a.p=JSON.stringify(t.props));var n=new XMLHttpRequest;n.open("POST",i+"/api/event",!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(a)),n.onreadystatechange=function(){4==n.readyState&&t&&t.callback&&t.callback()}}function n(){a("pageview")}function c(e){for(var t=e.target;t&&(void 0===t.tagName||"a"!=t.tagName.toLowerCase()||!t.href);)t=t.parentNode;t&&t.href&&plausible("Outbound Link: Click",{meta:{url:t.href}}),t.target&&!t.target.match(/^_(self|parent|top)$/i)||(setTimeout(function(){o.href=t.href},150),e.preventDefault())}try{var p,u=r.history;u.pushState&&(p=u.pushState,u.pushState=function(){p.apply(this,arguments),n()},r.addEventListener("popstate",n)),r.addEventListener("load",function(){for(var e=s.getElementsByTagName("a"),t=0;t<e.length;++t){var a=e[t];a.host!==o.host&&a.addEventListener("click",c)}});var f=r.plausible&&r.plausible.q||[];r.plausible=a;for(var d=0;d<f.length;d++)a.apply(this,f[d]);"prerender"===s.visibilityState?s.addEventListener("visibilitychange",function(){t||"visible"!==s.visibilityState||(t=!0,n())}):n()}catch(e){console.error(e),(new Image).src=i+"/api/error?message="+encodeURIComponent(e.message)}}(window,"<%= base_url %>");
\ No newline at end of file
diff --git a/priv/tracker/js/plausible.outbound-links.js b/priv/tracker/js/plausible.outbound-links.js
new file mode 100644
index 0000000000..f7b891f7b3
--- /dev/null
+++ b/priv/tracker/js/plausible.outbound-links.js
@@ -0,0 +1 @@
+!function(r,i){"use strict";var o=r.location,s=r.document,e=s.querySelector('[src*="'+i+'"]'),l=e&&e.getAttribute("data-domain"),t=!1;function a(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(o.hostname)||"file:"===o.protocol)return console.warn("Ignoring event on localhost");var a={};a.n=e,a.u=o.href,a.d=l,a.r=s.referrer||null,a.w=r.innerWidth,t&&t.meta&&(a.m=JSON.stringify(t.meta)),t&&t.props&&(a.p=JSON.stringify(t.props));var n=new XMLHttpRequest;n.open("POST",i+"/api/event",!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(a)),n.onreadystatechange=function(){4==n.readyState&&t&&t.callback&&t.callback()}}function n(){a("pageview")}function c(e){for(var t=e.target;t&&(void 0===t.tagName||"a"!=t.tagName.toLowerCase()||!t.href);)t=t.parentNode;t&&t.href&&plausible("Outbound Link: Click",{meta:{url:t.href}}),t.target&&!t.target.match(/^_(self|parent|top)$/i)||(setTimeout(function(){o.href=t.href},150),e.preventDefault())}try{var p,u=r.history;u.pushState&&(p=u.pushState,u.pushState=function(){p.apply(this,arguments),n()},r.addEventListener("popstate",n)),r.addEventListener("load",function(){for(var e=s.getElementsByTagName("a"),t=0;t<e.length;++t){var a=e[t];a.host!==o.host&&a.addEventListener("click",c)}});var f=r.plausible&&r.plausible.q||[];r.plausible=a;for(var d=0;d<f.length;d++)a.apply(this,f[d]);"prerender"===s.visibilityState?s.addEventListener("visibilitychange",function(){t||"visible"!==s.visibilityState||(t=!0,n())}):n()}catch(e){console.error(e),(new Image).src=i+"/api/error?message="+encodeURIComponent(e.message)}}(window,"<%= base_url %>");
\ No newline at end of file
diff --git a/tracker/compile.js b/tracker/compile.js
index dbb7b4fedf..1e95edf49d 100644
--- a/tracker/compile.js
+++ b/tracker/compile.js
@@ -17,5 +17,7 @@ function compilefile(input, output, templateVars = {}) {
compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.js'))
compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.hash.js'), {hashMode: true})
+compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.outbound-links.js'), {outboundLinks: true})
+compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.hash.outbound-links.js'), {hash: true, outboundLinks: true})
compilefile(relPath('src/p.js'), relPath('../priv/tracker/js/p.js'))
fs.copyFileSync(relPath('../priv/tracker/js/plausible.js'), relPath('../priv/tracker/js/analytics.js'))
diff --git a/tracker/src/plausible.js b/tracker/src/plausible.js
index fc2b7481ce..6ee5f13895 100644
--- a/tracker/src/plausible.js
+++ b/tracker/src/plausible.js
@@ -51,6 +51,38 @@
}
}
+ {{#if outboundLinks}}
+ function trackOutboundLink(event) {
+ var link = event.target;
+ while (link && (typeof link.tagName == 'undefined' || link.tagName.toLowerCase() != 'a' || !link.href)) {
+ link = link.parentNode;
+ }
+
+ if (link && link.href) {
+ plausible('Outbound Link: Click', {meta: {url: link.href}})
+ }
+
+ // Delay navigation so that Plausible is notified of the click
+ if(!link.target || link.target.match(/^_(self|parent|top)$/i)) {
+ setTimeout(function() { location.href = link.href; }, 150);
+ event.preventDefault();
+ }
+ }
+
+ function registerOutboundLinkEvents() {
+ window.addEventListener('load', function() {
+ var links = document.getElementsByTagName('a')
+
+ for (var i = 0; i < links.length; ++i) {
+ var link = links[i]
+ if (link.host !== location.host) {
+ link.addEventListener('click', trackOutboundLink);
+ }
+ }
+ });
+ }
+ {{/if}}
+
try {
var his = window.history
if (his.pushState) {
@@ -65,6 +97,9 @@
{{#if hashMode}}
window.addEventListener('hashchange', page)
{{/if}}
+ {{#if outboundLinks}}
+ registerOutboundLinkEvents()
+ {{/if}}
var queue = (window.plausible && window.plausible.q) || []