From 5ff3fbcb11400323045ceb6476a51a5613bdb9aa Mon Sep 17 00:00:00 2001 From: rickykuo666 Date: Wed, 4 Sep 2024 14:59:14 +0100 Subject: [PATCH] update title tag. inject script after consent --- components/CookieBanner.tsx | 25 +++++++++++++++++++++++++ pages/_document.tsx | 16 ---------------- pages/index.tsx | 2 +- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/components/CookieBanner.tsx b/components/CookieBanner.tsx index 6f4a27f..a5f8ea7 100644 --- a/components/CookieBanner.tsx +++ b/components/CookieBanner.tsx @@ -14,6 +14,28 @@ import { PrimaryButton } from './buttons/PrimaryButton' import { SecondaryButton } from './buttons/SecondaryButton' import Cookies from 'js-cookie' +function injectGoogleAnalyticsScripts() { + const scriptTag1 = document.createElement('script') + scriptTag1.setAttribute('strategy', 'afterInteractive') + scriptTag1.setAttribute( + 'src', + 'https://www.googletagmanager.com/gtag/js?id=G-39LG2721KV' + ) + + const scriptTag2 = document.createElement('script') + scriptTag2.setAttribute('id', 'google-analytics') + scriptTag2.setAttribute('strategy', 'afterInteractive') + scriptTag2.innerHTML = ` + window.dataLayer = window.dataLayer || []; + function gtag(){dataLayer.push(arguments);} + gtag('js', new Date()); + gtag('config', 'G-39LG2721KV'); + ` + + document.head.appendChild(scriptTag1) + document.head.appendChild(scriptTag2) +} + export const CookieBanner = () => { const [isOpen, setIsOpen] = useState(false) @@ -21,11 +43,14 @@ export const CookieBanner = () => { const consent = Cookies.get('cookie-consent') if (!consent) { setIsOpen(true) + } else if (consent === 'accepted') { + injectGoogleAnalyticsScripts() } }, []) const handleAccept = () => { Cookies.set('cookie-consent', 'accepted', { expires: 365 }) + injectGoogleAnalyticsScripts() setIsOpen(false) } diff --git a/pages/_document.tsx b/pages/_document.tsx index 5970a61..1f18aff 100644 --- a/pages/_document.tsx +++ b/pages/_document.tsx @@ -6,22 +6,6 @@ export default function Document() { -