I am using a standard GA4 implementation, but I am having trouble sending events to GA when inserting a script [validation.js] onto the page via top.document.body.appendChild. This is done to run an out-of-page popup form on ads manager.
<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XXXXXXX');
</script>
The script contains form validation and is hosted on DFP/GAM Google Ads Manager. The validation part works, but when I try to send the event to Analytics I get Gtag not defined.
gtag('event', 'lead_collection');
The GA4 tag is just plain placed on the site. The validation.js and html for the form are added via top.document.body.appendChild. Removing the async attribute from https://www.googletagmanager.com/gtag/js?id=XXXXXXX did not help.
when the validation.js script is just included within the html of the parent page all works fine, but when the script is added using top.document.body.appendChild from the ad iframe I get Gtag not defined.