Javascript 仅在Next.js中同意后才允许加载google analytics
我将google analytics集成到next.js中——也就是说,我遵循了以下指南: 这很好,现在的问题是我需要允许在cookie同意后才加载google analytics,我现在将我的cookie同意以以下格式存储在localStorage中:Javascript 仅在Next.js中同意后才允许加载google analytics,javascript,reactjs,google-analytics,next.js,Javascript,Reactjs,Google Analytics,Next.js,我将google analytics集成到next.js中——也就是说,我遵循了以下指南: 这很好,现在的问题是我需要允许在cookie同意后才加载google analytics,我现在将我的cookie同意以以下格式存储在localStorage中: checkboxValues = { necessary: true, statistics: false, marketing: false, }; 现在我需要检查localStorage.getItem('acceptCo
checkboxValues = {
necessary: true,
statistics: false,
marketing: false,
};
现在我需要检查localStorage.getItem('acceptCookies')
并确保仅当统计信息:true
时才加载google analytics
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>
);
}
}
从“next/Document”导入文档,{Html,Head,Main,NextScript};
从“./utils/gtag”导入{GA_跟踪_ID}”;
导出默认类MyDocument扩展文档{
render(){
返回(
{/*全局站点标签(gtag.js)-谷歌分析*/}
);
}
}
我不可能在
render()
之前检查localStorage,因为localStorage仅在componentDidMount
之后可用。坚持这一点,任何方向?都有内置的同意功能:
所以你在你的情况下加上
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,
});
`
}}
/>
我不认为这符合GDPR,欧洲法律甚至不允许加载脚本,即使它不会跟踪?我会尽力为我的声明找到一个来源。这些是谷歌提供的建议:@roko我认为你说的没有道理。你能给你的陈述添加资源吗?
if(consent){
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
}