Search code examples
javascriptreactjsgoogle-tag-manager

How to add condition in index.html file in react js


I want to use the google tag manager script just for the signup page. I don't want them for other pages. How can I add a condition in the index.html file in react to get the current URL?

I have already added the code to check if the environment is in production or not. This was the code

<% if (process.env.NODE_ENV === 'production') { %>
  <!-- Meta Pixel Code -->
  <script>
   ...
  </script>
<% } %>

But now to get the URL or pathname when I give the below code I'm getting a "window not defined" error. Do we have a way to get the URL in index.html file for react?

<% if (window.location.pathname === '/signup') { %>

Solution

  • Create a component like this

        export default function TrackingPixels(props) {
      
      useEffect(() => {
        return () => {
          handleRemoveScripts();
        }
      }, []);
        
      useEffect(() => {
    
        GoogleTagManager(value);
    
        return () => {
          handleRemoveScripts();
        }
      }, [(props.pagePixel || props.resourceCenterPixel)]);
    
      const handleRemoveScripts = () => {
        for (let id of elementIds) {
          removeScript(id);
        }
      }
    
      return null
    }
    
    function createScript(id, scriptText, src, async) {
      var script = document.createElement("script")
    
      if(id) {
        script.setAttribute("id", id)
      }
    
      if(src) {
        script.setAttribute("src", src);
      }
    
      if(async) {
        script.async = true;
      }
    
      if(scriptText) {
        script.appendChild(document.createTextNode(scriptText));
      }
    
      try {
        document.head.appendChild(script);
      } catch (e) {
        script.text = scriptText;
        document.head.appendChild(script);
      }
    }
    
    function noScriptForGTM(id, url) {
      var script = document.createElement("noscript")
      script.setAttribute("id", id)
      var x = document.createElement("iframe");
      x.setAttribute("src", url);
      x.setAttribute("width", "0")
      x.setAttribute("height", "0")
      x.setAttribute("style", "display:none;visibility:hidden")
      script.appendChild(x);
    
      var body = document.getElementsByTagName("body")[0];
      body.insertBefore(script, body.firstChild);
    }
    
    function removeScript(scriptId) {
       var elements = document.querySelectorAll(`#${scriptId}`);
       elements.forEach((element)=> {
        if (element) {
            element.parentNode.removeChild(element);
          }
        })
    }
    
    function GoogleTagManager(value) {
    
      if(!value) {
        return false;
      }
    
      const id = "google-tag-manager"
      const scriptText = `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
      new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
      j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
      'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
      })(window,document,'script','dataLayer','${value}');`
      const url = `https://www.googletagmanager.com/ns.html?id=${value}`
      noScriptForGTM(id, url);
      createScript(id, scriptText, null, false);
    
      return false;
    }
    

    And Add it in your signup page.