Last active
October 16, 2024 11:14
-
-
Save Pamps/461f91196d92ce3fc9308eee58b49add to your computer and use it in GitHub Desktop.
Get value from GTM, and update a form input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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