如何在 document.js nextjs 中禁用谷歌分析

Re-*_*lo 6 javascript reactjs next.js

当用户第一次访问网站时,他们可以选择接受或拒绝跟踪 cookie。如果他们拒绝,我会设置一个值为 false 的 cookie。我想使用 cookie 的值来有条件地运行 gtag 脚本。我尝试访问自定义 document.js 中的 cookie,但 getInitialProps 中的 req/res 未定义,并且 document.js 仅在服务器端运行,因此我无法访问浏览器 cookie。我怎样才能有条件地注入谷歌分析脚本?


class MyDocument extends Document {
    static async getInitialProps (ctx) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...initialProps, lang: ctx.query.lng}
    }

    render () {

        return (
            <Html lang={this.props.lang}>
                <Head>
                    <link
                        rel="stylesheet"
                        href="https://fonts.googleapis.com/css2?family=Poppins&display=swap"
                    />

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

export default MyDocument

Run Code Online (Sandbox Code Playgroud)

Ram*_*kay 0

未显示您如何设置 cookie,但将其设置为httponlysecure将阻止客户端访问 - 您可以省略它,并且 cookie 将在客户端可用,或者您可以使用webstorage API 并避免 cookie 路由。

一旦您拥有客户端访问权限,您就可以将脚本嵌入设置为有条件的。