问题描述
说明:
此代码有效(使用 gatsby develop 或 gatsby build && gatsby serve),但是如果我在没有 onAccept={() => window.location.reload()} 的情况下执行我的代码,则无法正常工作,因为只需加载我的 cookie - > (gatsby-gdpr-google-analytics = true) 但没有同时加载 ga cookie,我必须使用 onAccept 刷新。知道如何在不强制刷新的情况下同时加载所有 cookie 吗?
我的代码:
// gatsby-config.js
{
resolve: `gatsby-plugin-gdpr-cookies`,options: {
googleAnalytics: {
trackingId: 'my_tracking_id',// leave empty if you want to disable the tracker
cookieName: 'gatsby-gdpr-google-analytics',// default
includeInDevelopment: true,head: true
},// defines the environments where the tracking should be available - default is ["production"]
environments: ['production','development']
},},
// index.js
import CookieConsent from "react-cookie-consent";
<CookieConsent
overlay
id="#consentModal"
location="bottom"
buttonText="ACCEPT"
declineButtonText="DECLINE"
cookieName="gatsby-gdpr-google-analytics"
expires={150}
enableDeclineButton
style={{
background: "black",display: "flex",padding: "10px"
}}
buttonStyle={{
display: "inline-flex",background: "#fff",color: "red",borderRadius: "4px",justifyContent: "middle",width: "85px",}}
declineButtonStyle={{
display: "inline-flex",background: "#ff5f56",color: "#fff",cursor: "pointer",width: "85px"
}}
onAccept={() => window.location.reload()} //I would like to remove this refresh
>
<p style={{ float: "left",}}> my text </p>
<p style={{ float: "left",}}>my text</p>
</CookieConsent>
解决方法
使用:
import CookieConsent from "react-cookie-consent";
import { useLocation } from "@reach/router"
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies'
<CookieConsent
overlay
id="#consentModal"
location="bottom"
buttonText="ACCEPT"
declineButtonText="DECLINE"
cookieName="gatsby-gdpr-google-analytics"
expires={150}
enableDeclineButton
style={{
background: "black",display: "flex",padding: "10px"
}}
buttonStyle={{
display: "inline-flex",background: "#fff",color: "red",borderRadius: "4px",justifyContent: "middle",width: "85px",}}
declineButtonStyle={{
display: "inline-flex",background: "#ff5f56",color: "#fff",cursor: "pointer",width: "85px"
}}
onAccept={() => {
initializeAndTrack(location)
}}
>
<p style={{ float: "left",}}> my text </p>
<p style={{ float: "left",}}>my text</p>
</CookieConsent>
gatsby-plugin-gdpr-cookies
支持 tracking without refreshing the page using some built-in consumers。
导入帮助程序后,您可以在 cookie 横幅回调中执行 initializeAndTrack(location)
。这将使用 gatsby-config.js
中的选项初始化插件,然后根据接受的 cookie/服务开始跟踪用户。