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) { %> - - <% } %>