【问题标题】:How to disable google analytics in document.js nextjs如何在 document.js nextjs 中禁用谷歌分析
【发布时间】:2021-04-03 06:47:09
【问题描述】:

当用户首次访问网站时,他们可以选择接受或拒绝跟踪 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

【问题讨论】:

  • 你可以有条件地将数据推送到GTM数据层,对吧?您可以访问脚本标签中的 cookie。

标签: javascript reactjs next.js


【解决方案1】:

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

一旦您在客户端具有访问权限,您就可以使脚本嵌入有条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2020-06-10
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    相关资源
    最近更新 更多