Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active November 17, 2021 14:43
Show Gist options
  • Save marklchaves/c46572f62b3c9624aef2f037e5869bad to your computer and use it in GitHub Desktop.
Save marklchaves/c46572f62b3c9624aef2f037e5869bad to your computer and use it in GitHub Desktop.
Send a form impression event to GA4 using gtag.js API.
(function() {
if (typeof gtag === 'undefined') {
console.log('[GA4] gtag is undefined.');
return;
}
const formElts = document.querySelectorAll('form');
let formName = '(not set)';
// If no forms, bail.
if (formElts.length === 0) return;
[...formElts].map((f) => {
console.log(`Got a form: ${f}`);
try {
formName = f.dataset.formName || f.getAttribute('id') || '(not set)';
console.log(`[GA4] Sending impression for form: ${formName}`);
// Changed the event name from FormImpression and parameter
// from FormName for MI compliance 18 June 2021.
gtag("event", "form_impression", {
'form_id': "'" + formName + "'",
});
} catch (e) {
console.log("[GA4] Something wrong happened when setting up event handling for forms.");
}
});
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment