您必须结合 Gatsby 插件并构建自己的 cookie 同意横幅或使用现成的组件来实现此目的。
首先AskaNor_29 建议您需要安装和配置gatsby-plugin-gdpr-cookies 插件。可以获取插件here。
在 gatsby-config.js 中配置插件
// In your gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-gdpr-cookies`,
options: {
googleAnalytics: {
trackingId: 'YOUR_GOOGLE_ANALYTICS_TRACKING_ID',
// Setting this parameter is optional
anonymize: true
},
facebookPixel: {
pixelId: 'YOUR_FACEBOOK_PIXEL_ID'
},
// Defines the environments where the tracking should be available - default is ["production"]
environments: ['production', 'development']
},
},
],
}
第二部分是显示 cookie 同意横幅或模式,以便用户做出选择。
为此,您可以使用react-cookie-consent npm 模块。你可以得到npm包here。
要使其与gatsby-plugin-gdpr-cookies 一起使用,您需要设置cookieName="gatsby-gdpr-google-analytics" 属性。
然后您将CookieConsent 组件放入您的layout.js 文件中,以便在用户首先访问的任何页面上激活它。
<CookieConsent
location="bottom"
buttonText="Accept"
declineButtonText="Decline"
cookieName="gatsby-gdpr-google-analytics">
This site uses cookies ...
</CookieConsent>
该组件采用许多道具,因此您可以调整行为和外观。
如果您希望同时设置 Google Analytics 和 Facebook Pixel cookie,可以使用回调函数接受/拒绝 cookie,您可以在其中添加自定义代码来设置这两个 cookie。
如果你有兴趣,我写了更长的how-to describing the steps。