next.js 允许google analytics仅在同意下一页加载,js

z31licg0  于 2023-04-30  发布在  Go
关注(0)|答案(2)|浏览(133)

我把Google Analytics整合到了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');并确保google analytics只在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之后可用。被这个卡住了,有方向吗?

cl25kdpy

cl25kdpy1#

有内置的同意功能: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”行 Package 在类似的同意行中,尽管这可能不是一个“完整”的解决方案,因为它只会停止页面浏览:

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

cx6n0qe32#

根据this blog post,您可以创建一个Cookie横幅组件,用于更新Google Analytics同意:

'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));
}

相关问题