Skip to content

Instantly share code, notes, and snippets.

@Pamps
Last active October 16, 2024 11:14
Show Gist options
  • Save Pamps/461f91196d92ce3fc9308eee58b49add to your computer and use it in GitHub Desktop.
Save Pamps/461f91196d92ce3fc9308eee58b49add to your computer and use it in GitHub Desktop.
Get value from GTM, and update a form input
/**
* Get value from GTM, and update a form input
*/
( function () {
window.addEventListener( "load", function () {
// Check for our form
const form = document.querySelector( '.our-form' );
if ( ! form ) return;
// Our field to populate
const input = '.our-input';
// We need to wait until GA has loaded
function checkGaLoaded () {
if ( typeof ga === 'function' ) {
console.log('Loaded :'+ ga);
// Connect to GA
ga( 'create', 'UA-xxxxxxxx-x', 'auto' );
// Get the data
const all = ga.getAll();
const pc = all[0];
const data = pc['model']['data']['ea'];
for ( const [key, value] of Object.entries( data ) ) {
if ( key === ':our_key' ) {
console.log('Found');
console.log(value);
// Update the form value
const our_input = document.getElementById( input );
if ( our_input ) {
our_input.value = value;
}
}
}
} else {
console.log('Not loaded');
setTimeout( checkGaLoaded, 500 );
}
}
checkGaLoaded();
} );
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment