Skip to content

Commit 54881a0

Browse files
Issue feat: Gogle analytic event changes for plp
1 parent 1031297 commit 54881a0

File tree

2 files changed

+55
-6
lines changed

2 files changed

+55
-6
lines changed

apps/learner-web-app/src/components/GoogleAnalyticsTracker/GoogleAnalyticsTracker.tsx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ const GoogleAnalyticsTracker = () => {
2323
console.log('Initializing GA for Themantic');
2424
initGA(`${process.env.NEXT_PUBLIC_MEASUREMENT_ID_THEMATIC}`);
2525
}
26+
else if(window.location.href.includes('plp') )
27+
{
28+
console.log('Initializing GA for PLP or PDP');
29+
initGA(`${process.env.NEXT_PUBLIC_MEASUREMENT_ID_PLP}`);
30+
}
2631
else
2732
initGA(`${process.env.NEXT_PUBLIC_MEASUREMENT_ID_POS}`);
2833
window.GA_INITIALIZED = true;

apps/learner-web-app/src/utils/googleAnalytics.ts

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,24 @@
11
import ReactGA from "react-ga4";
22

3+
declare global {
4+
interface Window {
5+
gtag?: (...args: unknown[]) => void;
6+
dataLayer?: unknown[];
7+
}
8+
}
9+
310
export const initGA = (measurementId: string) => {
411
ReactGA.initialize(measurementId);
512
};
613

714
export const logPageView = (url: string) => {
15+
if(localStorage.getItem('userProgram'))
16+
{
17+
ReactGA.send({ hitType: "pageview", page: url , program: localStorage.getItem('userProgram')});
18+
return;
19+
20+
}
21+
else
822
ReactGA.send({ hitType: "pageview", page: url });
923
};
1024

@@ -19,10 +33,40 @@ export const logEvent = ({
1933
label?: string;
2034
value?: number;
2135
}) => {
22-
ReactGA.event({
23-
action,
24-
category,
25-
label,
26-
value,
27-
});
36+
if (typeof window === "undefined") return;
37+
38+
const userProgram = localStorage.getItem('userProgram');
39+
40+
// Build event parameters for GA4
41+
const eventParams: Record<string, string | number> = {
42+
event_category: category,
43+
};
44+
45+
// Add optional fields
46+
if (label) {
47+
eventParams.event_label = label;
48+
}
49+
if (value !== undefined) {
50+
eventParams.value = value;
51+
}
52+
53+
// Add program name if available (custom parameter)
54+
if (userProgram) {
55+
console.log('userProgram', userProgram);
56+
eventParams.program = userProgram;
57+
}
58+
59+
// Use gtag directly to send event with custom parameters
60+
// This ensures custom parameters like 'program' are sent to GA4
61+
if (window.gtag && typeof window.gtag === 'function') {
62+
window.gtag('event', action, eventParams);
63+
} else {
64+
// Fallback to ReactGA.event if gtag is not available
65+
ReactGA.event({
66+
action,
67+
category,
68+
label,
69+
value,
70+
});
71+
}
2872
};

0 commit comments

Comments
 (0)