只有在Next.js中同意后,才允许加载谷歌分析



我将谷歌分析集成到了next.js中——也就是说,我遵循了以下指南:

  1. https://frontend-digest.com/using-nextjs-with-google-analytics-and-typescript-620ba2359dea
  2. https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics

这很好,现在的问题是,我只需要在cookie同意后才允许加载谷歌分析,我现在只需将我的cookie同意存储在localStorage中,格式为:

checkboxValues = {
necessary: true,
statistics: false,
marketing: false,
};

现在我需要检查localStorage.getItem('acceptCookies');,并确保只有在statistics: true时才加载谷歌分析。

import Document, { Html, Head, Main, NextScript } from "next/document";
import { GA_TRACKING_ID } from "../utils/gtag";
export default class MyDocument extends Document {
render() {
return (
<Html>
<Head>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

我无法在render()之前检查localStorage,因为localStorage仅在componentDidMount之后可用。被这个卡住了,有方向吗?

有内置的同意功能:https://developers.google.com/gtagjs/devguide/consent

所以你在你的情况下添加

gtag('consent', 'default', {
'analytics_storage': 'denied'
});

所以它看起来像:

<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
//this defaults to denying
gtag('consent', 'default', {
'analytics_storage': 'denied'
});
gtag('js', new Date());
//check for consent, you'll need to write your own function here, but you get the idea
if(consentGranted){
gtag('consent', 'update', {
'analytics_storage': 'granted'
});
}
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`
}}
/>

或者,您可以将";config";排在类似的同意线上,尽管这可能不是"同意";完整的";解决方案,因为它只会停止页面浏览:

if(consent){    
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
}

根据这篇博客文章,你可以创建一个cookie横幅组件,更新谷歌分析同意:

'use client';
import { getLocalStorage, setLocalStorage } from '@/lib/storageHelper';
import { useState, useEffect } from 'react';
export default function CookieBanner(){
const [cookieConsent, setCookieConsent] = useState(false);
useEffect (() => {
const storedCookieConsent = getLocalStorage("cookie_consent", null)
setCookieConsent(storedCookieConsent)
}, [setCookieConsent])

useEffect(() => {
const newValue = cookieConsent ? 'granted' : 'denied'
window.gtag("consent", 'update', {
'analytics_storage': newValue
});
setLocalStorage("cookie_consent", cookieConsent)
}, [cookieConsent]);
return (
...

当用户接受cookie同意时,只需调用onClick={() => setCookieConsent(true)}

更新:storageHelper看起来像这样:

import "client-only";
export function getLocalStorage(key: string, defaultValue:any){
const stickyValue = localStorage.getItem(key);
return (stickyValue !== null && stickyValue !== 'undefined')
? JSON.parse(stickyValue)
: defaultValue;
}
export function setLocalStorage(key: string, value:any){
localStorage.setItem(key, JSON.stringify(value));
}

最新更新