I'm working on a Gatsby.js project that displays ads correctly in production, but not in localhost.
An iframe is supposed to be inserted into the Ad component via a script that is generated by the 'gatsby-browser.js' file. To facilitate this, I've also added another script in the 'gatsby-ssr.js' file to append Google Tags to the Window object, since I was having trouble doing this via the 'onClientEntry' function.
So far, I can generate the required Window objects, and append the script tag to the head tag in the HTML document, but still cannot generate the iframe.
Ad component
import React, { Component } from 'react' class Ad extends Component { componentDidMount(){ const script=document.createElement('script') script.src=`${adEmbedCodeURL}` script.defer=true; script.setAttribute("data-can-ad","true") this.instance.appendChild(script) } render() { return ( <div className=`${class-name}` ref={el => (this.instance = el)} > <p>Advertisement</p> </div> ) } } export default AdMPU
gatsby-browser.js
export const onClientEntry= () => { if (typeof __canGDPR == 'function') { console.log('onClientEntry') window.__canGDPR(function() { console.log('onClientEntry - CANS') var createScript = function(url, callback) { var script = document.createElement('script'); script.src = url; if (callback) { script.onload = callback; }document.getElementsByTagName('script')[0].appendChild(script); }; createScript(`https://www.googletagmanager.com/gtag/js?id=${containerID}`); window.dataLayer = window.dataLayer || []; function gtag(){ window.dataLayer.push(arguments); }gtag('js', new Date()); gtag('config', `${containerID}`); }); }; } export const onRouteUpdate = () => { console.log('onRouteUpdate'); if (typeof __canGDPR == 'function') { window.__canGDPR(function() { console.log('onRouteUpdate - CANS') var createScript = function(url, callback) { var script = document.createElement('script'); script.src = url; if (callback) { script.onload = callback; }document.getElementsByTagName('script')[0].appendChild(script); }; createScript(`https://www.googletagmanager.com/gtag/js?id=${containerID}`); window.dataLayer = window.dataLayer || []; function gtag(){ window.dataLayer.push(arguments); }gtag('js', new Date()); gtag('config', `${containerID}`); }); }; }
gatsby-ssr.js
import React from 'react' export const onRenderBody = ({ setHeadComponents }) => { setHeadComponents ([ <script key="SGCCansAds" src=`${adEmbedCodeURL}` />, <script key="jQuery" src="https://code.jquery.com/jquery-3.3.1.min.js" />, <script key="gtm-script" async src=`https://www.googletagmanager.com/gtag/js?id=${containerID}` />, <script key="gtm-initializer" dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){ window.dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', `${containerID}`); `, }} />, ]) }