From bc37ec400c20bc5ba7170e71663a4adb8c2ec6d6 Mon Sep 17 00:00:00 2001 From: Thomas Weber Date: Tue, 27 Oct 2020 20:48:42 -0500 Subject: [PATCH] Make analytics part of the bundle Instead of loading an external script, put the logic in the bundle itself This gives us more control over it, so now we: - do not include project IDs - delay events until idle --- src/lib/analytics.js | 47 +++++++++++++++++++++++++++++++++++++++- src/playground/index.ejs | 3 --- webpack.config.js | 4 +++- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/lib/analytics.js b/src/lib/analytics.js index 179ffb40a..3f466cd79 100644 --- a/src/lib/analytics.js +++ b/src/lib/analytics.js @@ -1,4 +1,49 @@ -// tw: disable analytics entirely +const plausibleHost = process.env.PLAUSIBLE_HOST; +const plausibleDomain = process.env.PLAUSIBLE_DOMAIN; +const isLocalhost = false && /^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*:)*?:?0*1$/.test(location.hostname); +const isFile = location.protocol === 'file:'; +const enabled = plausibleHost && plausibleDomain && !isLocalhost && !isFile; + +if (enabled) { + const sendEvent = eventName => { + // Delay analytics events until idle, we don't need to run them immediately. + (window.requestIdleCallback || window.setTimeout)(() => { + const url = new URL(location.href); + + url.pathname = url.pathname + // Don't include project IDs + .replace(/\d/g, '') + // Removing project IDs might result in multiple slashes: //editor, so merge multiple slashes into one + .replace(/\/+/g, '/'); + + const req = new XMLHttpRequest(); + req.open('POST', `${plausibleHost}/api/event`, true); + req.setRequestHeader('Content-Type', 'text/plain'); + req.send(JSON.stringify({ + n: eventName, + u: url.href, + d: plausibleDomain, + r: document.referrer || null, + w: window.innerWidth + })); + }); + }; + + const trackPageview = () => { + sendEvent('pageview'); + }; + + const originalPushState = history.pushState; + history.pushState = (a, b, c) => { + originalPushState.call(history, a, b, c); + trackPageview(); + }; + window.addEventListener('popstate', trackPageview); + + trackPageview(); +} + +// Mock GoogleAnalytics to disable Scratch's events const GoogleAnalytics = { event () {} }; diff --git a/src/playground/index.ejs b/src/playground/index.ejs index 61a1e27d9..4cfc7742a 100644 --- a/src/playground/index.ejs +++ b/src/playground/index.ejs @@ -28,9 +28,6 @@ <% } %> - <% if (htmlWebpackPlugin.options.plausible) { %> - - <% } %>