Skip to content

Commit

Permalink
fix: track pageleave event with posthog
Browse files Browse the repository at this point in the history
  • Loading branch information
olegshilov committed Aug 8, 2024
1 parent 434a6a3 commit f17d3ff
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 28 deletions.
40 changes: 12 additions & 28 deletions src/components/posthog-page-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,21 @@ export function PostHogPageView() {
const posthog = usePostHog();

useEffect(() => {
const trackPageView = () => {
if (pathname && posthog) {
let url = window.origin + pathname;
if (searchParams.toString()) {
url += `?${searchParams.toString()}`;
}
posthog.capture('$pageview', {
$current_url: url,
$set: {
$browser_language: window.navigator.language,
},
});
}
};

const trackPageLeave = () => {
if (posthog) {
posthog.capture('$pageleave', {});
}
};

// Track pageviews
trackPageView();
if (pathname && posthog) {
let url = window.origin + pathname;

// Add event listener to track page leave
window.addEventListener('beforeunload', trackPageLeave);
if (searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}

// Cleanup the event listener when the component unmounts
return () => {
window.removeEventListener('beforeunload', trackPageLeave);
};
posthog.capture('$pageview', {
$current_url: url,
$set: {
$browser_language: window.navigator.language,
},
});
}
}, [pathname, searchParams, posthog]);

return null;
Expand Down
1 change: 1 addition & 0 deletions src/providers/posthog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function PHProvider({ children }: PropsWithChildren) {
api_host: '/api/ingest',
ui_host: env.NEXT_PUBLIC_POSTHOG_HOST,
capture_pageview: false,
capture_pageleave: true,
});

if (!phInstance) {
Expand Down

0 comments on commit f17d3ff

Please sign in to comment.