我已经使用 gatsby-pluging-google-gtag 插件设置了 Google Analytics,并带有程序化退出功能,如下所示:
1。安装插件
npm install gatsby-plugin-google-gtag
2。将插件添加到您的gatsby-config.js
{
resolve: `gatsby-plugin-google-gtag`,
options: {
// You can add multiple tracking ids and a pageview event will be fired for all of them.
trackingIds: [
"UA-XXXXXXXXX-X", // Google Analytics / GA
],
// puts tracking script in the head instead of the body
head: true,
// enable ip anonymization (relevant for GDPR)
anonymize: true,
},
},
3。在隐私页面中添加按钮以允许用户选择退出 Google Analytics
要以编程方式退出 Google Analytics,您需要在按钮的 onClick 处理程序中设置退出 cookie。
<button onClick={() => {
// TODO: replace UA-XXXXXXXXX-X with your tracking id. Make sure to not delete any other characters
document.cookie = "ga-disable-UA-XXXXXXXXX-X=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/";
window.disableStr = 1;
alert("opt out successful");
}}>
onClick 处理程序基本上与Gatsby suggests in their documentation 几乎相同
请注意,您需要使用 Google Analytics(分析)管理面板中的正确跟踪 ID 替换 UA-XXXXXXXXX-X。您也可以考虑使用 env var 作为跟踪 id 以保持代码库 DRY。
注意事项
该插件在您运行时不会加载 Google Analytics:
gatsby develop
你需要跑
gatsby build && gatsby serve
还请确保您的浏览器不会从一开始就阻止分析脚本(例如 Brave 浏览器)。否则,它将无法正常工作。单击按钮后,您应该会在开发者控制台中看到一个额外的 cookie。