Google同意模式使用Gatsby实施

发布于 2025-02-11 05:29:40 字数 1293 浏览 2 评论 0原文

我正在关注此 nofollow noreferrer“> tutorial”将cookie添加到我的网站上! 通过使用gatsby.js,我不确定如何添加这些代码:

<!-- The initial config of Consent Mode -->
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
</script>
​
<!-- Cookie Information Pop-up Script is required for the SDK -->
<script id="CookieConsent" src="https://policy.app.cookieinformation.com/uc.js" data-culture="EN" type="text/javascript"></script>
​
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING-ID"></script>
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
​
gtag('config', 'TRACKING-ID');
</script>
​
</head>
<body>

您是否知道如何在盖茨比(Gatsby)实现此代码,是否有任何库或其他有助于实现这些脚本的东西! 谢谢

I am following this tutorial about implementing google consent mode to add cookies to my website !
By using Gatsby.js I am not sure how to add these codes :

<!-- The initial config of Consent Mode -->
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('consent', 'default', {
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 1500,
});
gtag('set', 'ads_data_redaction', true);
</script>
​
<!-- Cookie Information Pop-up Script is required for the SDK -->
<script id="CookieConsent" src="https://policy.app.cookieinformation.com/uc.js" data-culture="EN" type="text/javascript"></script>
​
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING-ID"></script>
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
​
gtag('config', 'TRACKING-ID');
</script>
​
</head>
<body>

Do you have any idea how to implement this code in Gatsby , is there any library or something that will help to implement these scripts !
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

御守 2025-02-18 05:29:40

该组件用作页面加载时应用的初始屏幕。

import React, { useState, useEffect } from 'react';

import { useLocation } from '@reach/router';
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';
import Cookies from 'js-cookie';

import CookieSettings from './Settings';

const CookieBanner = () => {
    const [showBanner, setShowBanner] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const location = useLocation();

    // showSettings -> use this state property to open a configuration
    // window which may open up more information on the cookie(s) being applied

    useEffect(() => {
        setShowBanner(Cookies.get('gatsby-gdpr-responded') !== 'true');
    }, [])

    useEffect(() => {
        initTracking();
    }, [Cookies.get('gatsby-gdpr-responded')])

    const initTracking = () => {
        initializeAndTrack(location)
    }

    const handleAccept = () => {
        Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
        handleCloseAll();
    }

    const handleDecline = () => {
        Cookies.remove('gatsby-gdpr-google-analytics');
        handleCloseAll();
    }

    const handleCloseAll = () => {
        setShowSettings(false);
        setShowBanner(false);

        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });
    }

    return (
        // add your component logic here
        // Take not of the different functions that are available above, like handleAccept / handleDecline / handleCloseAll 
        // handleCloseAll -> if a user declines / closes the banner
        // handleAccept -> a button to accept by default
        // handleDecline -> a button to decline the cookies

    )
}

export default CookieBanner

下一个组件更多是配置屏幕,它提供有关所应用的cookie的更多信息,如果您注意切换的导入,我们会使用切换来允许用户在任何时候专门关闭或关闭其cookie,您当然,如果您有很多GDPR合规,则可能需要创建单独的功能来处理删除cookie的函数,或者是通过要删除 /应用的cookie名称的可重复使用功能。

import React, { useState } from 'react';

import Cookies from 'js-cookie';

import Button from '@components/Button';
import Toggle from '@components/Inputs/Toggle';

const CookieSettings = ({
    handleAccept,
    handleDecline,
    initTracking,
    handleCloseAll
}) => {
    const [trackAnalytics, setTrackAnalytics] = useState(Cookies.get('gatsby-gdpr-google-analytics') === 'true')

    const handleToggle = () => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        setTrackAnalytics((prevState) => {
            if (prevState) {
                Cookies.remove('gatsby-gdpr-google-analytics');
            } else {
                Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
            }

            return !prevState
        })

        initTracking();
    }

    return (
        // your JSX code here
    )
}

export default CookieSettings;

编辑


// A some what reusable function that you can pass a cookie name too and switch over the name provided and set the required cookie.
const handleToggle = (cookieName) => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        switch (cookieName) {
            case 'gatsby-gdpr-google-analytics':
                return setTrackAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            case 'gatsby-gdpr-google-tagmanager':
                return setTagAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            case 'gatsby-gdpr-facebook-pixel':
                return setFacebookAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            default:
                break;
        }

        initTracking()
    }

// A JSX toggle within your cookie setting
<Toggle active={trackAnalytics} toggleActive={() => handleToggle('gatsby-gdpr-google-analytics')} />
// The toggle component itself
import React from 'react';
import cx from 'classnames'
import PropTypes from 'prop-types'
import './styles.scss';

export default function Toggle({
    active = false,
    toggleActive,
}) {

    return (
        <div onClick={typeof toggleActive === 'function' && toggleActive} className={cx('toggle relative cursor-pointer', { active })} />
    )
}


Toggle.propTypes = {
    active: PropTypes.bool,
    toggleActive: PropTypes.func.isRequired
}

Toggle.defaultProps = {
    active: false,
}

This component is used as the initial screen that applies when the page loads.

import React, { useState, useEffect } from 'react';

import { useLocation } from '@reach/router';
import { initializeAndTrack } from 'gatsby-plugin-gdpr-cookies';
import Cookies from 'js-cookie';

import CookieSettings from './Settings';

const CookieBanner = () => {
    const [showBanner, setShowBanner] = useState(false);
    const [showSettings, setShowSettings] = useState(false);
    const location = useLocation();

    // showSettings -> use this state property to open a configuration
    // window which may open up more information on the cookie(s) being applied

    useEffect(() => {
        setShowBanner(Cookies.get('gatsby-gdpr-responded') !== 'true');
    }, [])

    useEffect(() => {
        initTracking();
    }, [Cookies.get('gatsby-gdpr-responded')])

    const initTracking = () => {
        initializeAndTrack(location)
    }

    const handleAccept = () => {
        Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
        handleCloseAll();
    }

    const handleDecline = () => {
        Cookies.remove('gatsby-gdpr-google-analytics');
        handleCloseAll();
    }

    const handleCloseAll = () => {
        setShowSettings(false);
        setShowBanner(false);

        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });
    }

    return (
        // add your component logic here
        // Take not of the different functions that are available above, like handleAccept / handleDecline / handleCloseAll 
        // handleCloseAll -> if a user declines / closes the banner
        // handleAccept -> a button to accept by default
        // handleDecline -> a button to decline the cookies

    )
}

export default CookieBanner

The next component is more of a Configuration screen, which provides more information on the cookies being applied, if you take note on the import of Toggle, we use a toggle to allow users to specifically toggle on or off their cookies at any point, you of course if you have many GDPR compliances, may want to either create separate functions that handle the removal of cookies or a reusable function that is passed the name of the cookie to be removed / applied.

import React, { useState } from 'react';

import Cookies from 'js-cookie';

import Button from '@components/Button';
import Toggle from '@components/Inputs/Toggle';

const CookieSettings = ({
    handleAccept,
    handleDecline,
    initTracking,
    handleCloseAll
}) => {
    const [trackAnalytics, setTrackAnalytics] = useState(Cookies.get('gatsby-gdpr-google-analytics') === 'true')

    const handleToggle = () => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        setTrackAnalytics((prevState) => {
            if (prevState) {
                Cookies.remove('gatsby-gdpr-google-analytics');
            } else {
                Cookies.set('gatsby-gdpr-google-analytics', true, { expires: 365 })
            }

            return !prevState
        })

        initTracking();
    }

    return (
        // your JSX code here
    )
}

export default CookieSettings;

EDIT


// A some what reusable function that you can pass a cookie name too and switch over the name provided and set the required cookie.
const handleToggle = (cookieName) => {
        Cookies.set('gatsby-gdpr-responded', true, { expires: 365 });

        switch (cookieName) {
            case 'gatsby-gdpr-google-analytics':
                return setTrackAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            case 'gatsby-gdpr-google-tagmanager':
                return setTagAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            case 'gatsby-gdpr-facebook-pixel':
                return setFacebookAnalytics((prevState) => {
                    if (prevState) {
                        Cookies.remove(cookieName);
                    } else {
                        Cookies.set(cookieName, true, {
                            expires: 365
                        });
                    }

                    return !prevState
                })
            default:
                break;
        }

        initTracking()
    }

// A JSX toggle within your cookie setting
<Toggle active={trackAnalytics} toggleActive={() => handleToggle('gatsby-gdpr-google-analytics')} />
// The toggle component itself
import React from 'react';
import cx from 'classnames'
import PropTypes from 'prop-types'
import './styles.scss';

export default function Toggle({
    active = false,
    toggleActive,
}) {

    return (
        <div onClick={typeof toggleActive === 'function' && toggleActive} className={cx('toggle relative cursor-pointer', { active })} />
    )
}


Toggle.propTypes = {
    active: PropTypes.bool,
    toggleActive: PropTypes.func.isRequired
}

Toggle.defaultProps = {
    active: false,
}

小红帽 2025-02-18 05:29:40

在Gatsby插件集线器中使用此插件
gatsby-plugin-gdpr-cookies

它将为您提供所需的内容,并且您可以在插件的选项中列出您想要跟踪的cookie +您希望提供的cookiename然后,可以从组件级别上使用cookie工具栏时从组件级别使用:

{
  resolve: `gatsby-plugin-gdpr-cookies`,
  options: {
    googleAnalytics: {
      trackingId: process.env.UA_TAG, // your UA tag goes here
      cookieName: `gatsby-gdpr-google-analytics`,
      anonymize: true,
      allowAdFeatures: false
    },
    environments: [`production`, `development`]
  },
},

它消除了必须用react-helmet将脚本注入脚本的用法,因为插件将为您处理脚本注入。

Use this plugin from the Gatsby Plugin Hub
gatsby-plugin-gdpr-cookies

It will provide you what you are looking for and also you can list in the options for the plugin which cookies you are looking to track + a cookieName you wish to provide which you can then work with from a component level when creating a cookie toolbar such as:

{
  resolve: `gatsby-plugin-gdpr-cookies`,
  options: {
    googleAnalytics: {
      trackingId: process.env.UA_TAG, // your UA tag goes here
      cookieName: `gatsby-gdpr-google-analytics`,
      anonymize: true,
      allowAdFeatures: false
    },
    environments: [`production`, `development`]
  },
},

It elimites the usage of having to inject a script into the head of the website with React-Helmet as the plugin will handle the script injection for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文