Skip to content

Commit 9b694a6

Browse files
committed
feat: implement segment link tracking, opt-in solution, track only Apify Trust Center
1 parent e3c46e0 commit 9b694a6

2 files changed

Lines changed: 63 additions & 1 deletion

File tree

src/plugins/docusaurus-plugin-segment/index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ module.exports = function (context, options) {
77
name: 'docusaurus-plugin-segment',
88

99
getClientModules() {
10-
return [path.resolve(__dirname, './segment')];
10+
return [
11+
path.resolve(__dirname, './segment'),
12+
path.resolve(__dirname, './linkTracking'),
13+
];
1114
},
1215

1316
injectHtmlTags() {
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)