|
| 1 | +import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; |
| 2 | + |
| 3 | +// Opt-in link trackers. Currently limited to Trust Center to avoid Segment noise - see https://github.com/apify/apify-docs/issues/2409. |
| 4 | +const LINK_TRACKERS = [ |
| 5 | + { |
| 6 | + test: (url) => url.hostname === 'trust.apify.com', |
| 7 | + element: 'trust-center-link', |
| 8 | + }, |
| 9 | + // Examples for future opt-in: |
| 10 | + // { test: (url) => !/(^|\.)apify\.com$/.test(url.hostname) } // all outbound |
| 11 | + // { test: () => true } // all links |
| 12 | +]; |
| 13 | + |
| 14 | +let installed = false; |
| 15 | + |
| 16 | +function handleLinkClick(event) { |
| 17 | + // auxclick fires for all non-primary buttons; only handle middle click (button === 1) |
| 18 | + if (event.type === 'auxclick' && event.button !== 1) return; |
| 19 | + if (process.env.NODE_ENV !== 'production' || !window.analytics) return; |
| 20 | + |
| 21 | + const anchor = event.target.closest('a[href]'); |
| 22 | + if (!anchor) return; |
| 23 | + |
| 24 | + let url; |
| 25 | + try { |
| 26 | + url = new URL(anchor.getAttribute('href'), window.location.href); |
| 27 | + } catch { |
| 28 | + return; |
| 29 | + } |
| 30 | + if (!/^https?:$/.test(url.protocol)) return; |
| 31 | + |
| 32 | + const tracker = LINK_TRACKERS.find(({ test }) => test(url)); |
| 33 | + if (!tracker) return; |
| 34 | + |
| 35 | + const isApifyDomain = /(^|\.)apify\.com$/.test(url.hostname); |
| 36 | + |
| 37 | + window.analytics.track('Clicked', { |
| 38 | + app: 'docs', |
| 39 | + element: tracker.element ?? 'link', |
| 40 | + button_text: anchor.textContent?.trim().slice(0, 200) || null, |
| 41 | + href: url.href, |
| 42 | + is_subdomain: isApifyDomain && url.hostname !== window.location.hostname, |
| 43 | + is_outbound: !isApifyDomain, |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +function installLinkClickTracker() { |
| 48 | + if (installed) return; |
| 49 | + installed = true; |
| 50 | + |
| 51 | + document.addEventListener('click', handleLinkClick, { capture: true }); |
| 52 | + document.addEventListener('auxclick', handleLinkClick, { capture: true }); |
| 53 | +} |
| 54 | + |
| 55 | +export default ExecutionEnvironment.canUseDOM ? { |
| 56 | + onRouteDidUpdate() { |
| 57 | + installLinkClickTracker(); |
| 58 | + }, |
| 59 | +} : null; |
0 commit comments