Skip to content

Commit 7e1f9a1

Browse files
committed
Track page_loaded event
1 parent 62386c0 commit 7e1f9a1

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

pages/_app.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,39 @@ if (typeof window === 'undefined') {
55

66
import "../styles/base.scss";
77
import { useState, useEffect } from "react";
8+
import { useRouter } from "next/router";
89

910
import SelectedContext from "../ctx/SelectedContext";
1011

1112
import { checkTheme } from "../utils/helpers";
13+
import { trackPageLoaded } from "../utils/gtm";
1214
import Nav from "../components/Nav";
1315
import SelectionBar from "../components/SelectionBar";
1416
import PopularContext from "../ctx/PopularContext";
1517
import { SessionProvider } from "next-auth/react";
1618

1719
function winstall({ Component, pageProps: { session, ...pageProps } }) {
20+
const router = useRouter();
21+
1822
const [selectedApps, setSelectedApps] = useState([]);
1923
const selectedAppValue = { selectedApps, setSelectedApps };
2024

2125
const [popular, setPopular] = useState([]);
2226
const popularApps = { popular, setPopular };
2327

28+
useEffect(() => {
29+
// Track page views on route change
30+
const handleRouteChange = (url) => {
31+
trackPageLoaded(url);
32+
};
33+
34+
router.events.on("routeChangeComplete", handleRouteChange);
35+
36+
return () => {
37+
router.events.off("routeChangeComplete", handleRouteChange);
38+
};
39+
}, [router.events]);
40+
2441
useEffect(() => {
2542
checkTheme();
2643

utils/gtm.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* Google Tag Manager DataLayer Helper
3+
*/
4+
5+
/**
6+
* Push a page view event to GTM dataLayer
7+
* @param {string} url - The page URL/path
8+
*/
9+
export const trackPageLoaded = (url) => {
10+
if (typeof window !== "undefined" && window.dataLayer) {
11+
window.dataLayer.push({
12+
event: "page_loaded",
13+
page_location: window.location.href,
14+
page_path: url,
15+
page_title: document.title
16+
});
17+
}
18+
};

0 commit comments

Comments
 (0)