React:如何在用户同意后手动加载 cookie 的脚本?

问题描述

所以我的 index.html 看起来像这样(<head> 中的一些 Google Tag Manager 和其余部分以及 <body> 中的 Facebook Pixel:

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="utf-8" />
    <Meta name="viewport" content="width=device-width,initial-scale=1" />
    ...
    <!-- Google Tag Manager (noscript) -->
    <noscript>
        <iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-ID"
            height="0"
            width="0"
            style="display: none; visibility: hidden"
        ></iframe>
    </noscript>
    <!-- End Google Tag Manager (noscript) -->
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!-- Facebook Pixel Code -->
    <script>
        !(function (f,b,e,v,n,t,s) {
            if (f.fbq) return;
            n = f.fbq = function () {
                n.callMethod
                    ? n.callMethod.apply(n,arguments)
                    : n.queue.push(arguments);
            };
            if (!f._fbq) f._fbq = n;
            n.push = n;
            n.loaded = !0;
            n.version = "2.0";
            n.queue = [];
            t = b.createElement(e);
            t.async = !0;
            t.src = v;
            s = b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t,s);
        })(
            window,document,"script","https://connect.facebook.net/en_US/fbevents.js"
        );
        fbq("init","id");
        fbq("track","PageView");
    </script>
    <noscript
        ><img
            height="1"
            width="1"
            style="display: none"
            src="https://www.facebook.com/tr?id=ID&ev=PageView&noscript=1"
    /></noscript>
    <!-- End Facebook Pixel Code -->

    <!-- Google Tag Manager (noscript) -->
    <noscript
        ><iframe
            src="https://www.googletagmanager.com/ns.html?id=GTM-ID"
            height="0"
            width="0"
            style="display: none; visibility: hidden"
        ></iframe
    ></noscript>
    <!-- End Google Tag Manager (noscript) -->
</body>

所以我现在的问题是如何在加载我的页面后手动添加它并确保脚本仍然执行

我尝试在带有 useEffect()document.append() 钩子中添加代码,但之后它没有执行脚本,也没有按照我想要的方式工作...

有什么方法可以很好地将其集成到 cookie 同意组件中吗?

我的 cookie 同意组件如下所示:

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

import { Wrapper,Button } from './Styles'

const CookiePopup = ({setPopupShown}) => {
  const [showCookies,setShowCookies] = useState(false);

  const cookieAccept = () => {
    setShowCookies(true);
    setPopupShown(true);
  }

  useEffect(() => {
    if(showCookies){
      localStorage.setItem('PopupShown','True');
    }
  },[showCookies])

  return (
    <Wrapper>
      <span>Consent Text</span>
      <Button onClick={cookieAccept}>Accept cookies</Button>
    </Wrapper>
  )
}

export default CookiePopup

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)