【发布时间】:2021-04-22 21:28:53
【问题描述】:
我将谷歌分析集成到 next.js - 也就是说,我遵循了这些指南:
- https://frontend-digest.com/using-nextjs-with-google-analytics-and-typescript-620ba2359dea
- 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'); 并确保仅在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 之后可用。卡住了,有什么方向吗?
【问题讨论】:
标签: javascript reactjs google-analytics next.js