From 707782a414e06d5b0e295d491d79923c56ab1e13 Mon Sep 17 00:00:00 2001 From: Fernando Lucchesi Date: Tue, 17 Oct 2023 10:25:05 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Collect=20analytics=20accordingly?= =?UTF-8?q?=20to=20cookies=20preferences=20#1843?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/lib/gtm.js | 1 + web/lib/hooks/useVideoAnalytics.ts | 14 +++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/web/lib/gtm.js b/web/lib/gtm.js index 1cdae64cb..f72b5a0e9 100644 --- a/web/lib/gtm.js +++ b/web/lib/gtm.js @@ -8,6 +8,7 @@ export const pageview = (url) => { } export const pushToDataLayer = (event, data) => { + console.log(event, data) window.dataLayer = window.dataLayer || [] window.dataLayer.push({ event: event, diff --git a/web/lib/hooks/useVideoAnalytics.ts b/web/lib/hooks/useVideoAnalytics.ts index 1b72a6d59..0bc19b4e9 100644 --- a/web/lib/hooks/useVideoAnalytics.ts +++ b/web/lib/hooks/useVideoAnalytics.ts @@ -1,5 +1,5 @@ import { pushToDataLayer } from '../../lib/gtm' -import { useEffect, useMemo, useCallback } from 'react' +import { useEffect, useMemo, useCallback, useState } from 'react' import useConsentState from './useConsentState' type GTMTitleType = { videoTitle: string | undefined } @@ -9,6 +9,14 @@ const GTM_PLAY_EVENT = 'video_play' const GTM_PAUSE_EVENT = 'video_pause' const useVideoAnalytics = (videoRef: VideoRefType, src: string, title?: string): void => { + const [allowAnalytics, setAllowAnalytics] = useState(false) + + useConsentState( + 'statistics', + () => setAllowAnalytics(true), + () => setAllowAnalytics(false), + ) + const GTM_TITLE: GTMTitleType = useMemo(() => ({ videoTitle: title || src }), [title, src]) const handlePlayEvent = useCallback(() => { @@ -22,7 +30,7 @@ const useVideoAnalytics = (videoRef: VideoRefType, src: string, title?: string): useEffect(() => { const videoElement = videoRef.current - if (!videoElement) return + if (!videoElement || !allowAnalytics) return videoElement.addEventListener('play', handlePlayEvent) videoElement.addEventListener('pause', handlePauseEvent) @@ -32,7 +40,7 @@ const useVideoAnalytics = (videoRef: VideoRefType, src: string, title?: string): videoElement.removeEventListener('play', handlePlayEvent) videoElement.removeEventListener('pause', handlePauseEvent) } - }, [videoRef, handlePlayEvent, handlePauseEvent]) + }, [allowAnalytics, videoRef, handlePlayEvent, handlePauseEvent]) } export default useVideoAnalytics