-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.js
More file actions
30 lines (25 loc) · 851 Bytes
/
Copy pathanalytics.js
File metadata and controls
30 lines (25 loc) · 851 Bytes
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
function getGoogleAnalyticsId() {
const id = String(process.env.GOOGLE_ANALYTICS_ID || "").trim();
return /^G-[A-Z0-9]+$/i.test(id) ? id : "";
}
function getGoogleAnalyticsTag() {
const id = getGoogleAnalyticsId();
if (!id) return "";
return `
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(id)}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag("js", new Date());
gtag("config", ${JSON.stringify(id)});
</script>`;
}
function injectGoogleAnalytics(html) {
const tag = getGoogleAnalyticsTag();
if (!tag || typeof html !== "string" || !html.includes("</head>")) {
return html;
}
return html.replace("</head>", `${tag}\n</head>`);
}
module.exports = { injectGoogleAnalytics };