gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:02:10 25 4
gpt4 key购买 nike

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


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

最佳答案

未显示您如何设置 cookie,但将其设置为 httponlysecure将阻止客户端访问 - 您可以省略它,cookie 将在客户端可用,或者您可以使用 webstorage API 并避免 cookie 路由。
一旦您在客户端具有访问权限,您就可以使脚本嵌入成为有条件的。

关于javascript - 如何在 document.js nextjs 中禁用谷歌分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65444710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com