-
-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathGTMProvider.tsx
More file actions
60 lines (48 loc) · 1.54 KB
/
Copy pathGTMProvider.tsx
File metadata and controls
60 lines (48 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { useEffect } from 'react';
declare global {
interface Window {
dataLayer: any[];
gtag: (...args: any[]) => void;
}
}
// eslint-disable-next-line @typescript-eslint/naming-convention
export function GTMProvider() {
useEffect(() => {
// Load GTM script
const script = document.createElement('script');
script.async = true;
script.src = `https://www.googletagmanager.com/gtm.js?id=GTM-5M9R7HFN`;
document.head.appendChild(script);
// Load Google Analytics script
const gaScript = document.createElement('script');
gaScript.async = true;
gaScript.src = `https://www.googletagmanager.com/gtag/js?id=G-8NNCCEN53X`;
document.head.appendChild(gaScript);
// Initialize GTM data layer
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'gtm.start': new Date().getTime(),
event: 'gtm.js',
});
// Initialize Google Analytics
window.gtag =
window.gtag ||
function (...args: any[]) {
window.dataLayer.push(args);
};
window.gtag('js', new Date());
window.gtag('config', 'G-8NNCCEN53X');
// Cleanup function
return () => {
const gtmScript = document.querySelector('script[src*="googletagmanager.com/gtm.js?id=GTM-5M9R7HFN"]');
if (gtmScript) {
document.head.removeChild(gtmScript);
}
const gaScript = document.querySelector('script[src*="googletagmanager.com/gtag/js?id=G-8NNCCEN53X"]');
if (gaScript) {
document.head.removeChild(gaScript);
}
};
}, []);
return null;
}