I’m trying to implement populating hidden fields with cookie data on a non-HTML, embedded HubSpot form. However, I run into this error:
document.querySelector('input[name="utm_campaign"]').value
//Error text:
VM57621:1 Uncaught TypeError: Cannot read properties of null (reading 'value')
at <anonymous>:1:53
(
This happens even when the form comes into view. In fact, the warning doesn’t go away until I inspect the element, find the hidden fields, and then try it again.
My code looks like this:
<script>
// Get URL from cookie
var campaignUrl = decodeURI(cookieUrl);
// Get utm params
var cookieParams = campaignUrl.split('?')[1];
console.log(cookieParams);
var individualParams = cookieParams.split('&')
var cookieStorage = {}
// loop through params and push to cookieStorage dictionary cookieStorage
individualParams.forEach(function(param) {
var paramKey = param.split('=')[0];
var paramVal = param.split('=')[1];
if (paramKey.includes('utm') || paramKey.includes('gtm')) {
cookieStorage[paramKey] = paramVal;
}
})
console.log(cookieStorage);
// attempt to substitute value of hidden fields with cookieStorage values
document.querySelector('input[name="utm_campaign"]').value=cookieStorage["utm_campaign"];
document.querySelector('input[name="utm_medium"]').value=cookieStorage["utm_medium"];
document.querySelector('input[name="utm_source"]').value=cookieStorage["utm_source"];
document.querySelector('input[name="utm_term"]').value=cookieStorage["utm_term"];
</script>
This works as intended all the way up to setting the document.querySelector values because, as mentioned, these are null until I interact with the actual source code.