'Get data from iFrame dataLayer, but get error: contentWindow = null

I am trying to get data from a HubSpot form into a custom javascript variable.

I can get the element to view in the colsule using querySelector, the code being as follows:

<script type="text/javascript">
var iframe = document.querySelector('iframe');
                                    
 var contactType = iframe.contentWindow.document.querySelector('[name="how_can_we_help_you"]').value;
  window.addEventListener("message", function(event) {
    if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmitted') {
      window.dataLayer.push({
        'event': 'hubspot-form-success',
        'hs-form-guid': event.data.id,
        'hs-form-contact' : contactType,
        'hs-form-contact1' : event.data
      });
    }
  });
</script>

I can then see the error:

Uncaught TypeError: Cannot read properties of null (reading 'contentWindow')
    at <anonymous>:1:64
    at gtm.js?id=GTM-WJPP59F:428:414
    at b (gtm.js?id=GTM-WJPP59F:429:337)
    at se (gtm.js?id=GTM-WJPP59F:87:769)
    at e (gtm.js?id=GTM-WJPP59F:211:34)
    at gtm.js?id=GTM-WJPP59F:37:130
    at Array.<anonymous> (gtm.js?id=GTM-WJPP59F:212:454)
    at Object.execute (gtm.js?id=GTM-WJPP59F:212:194)
    at hs (gtm.js?id=GTM-WJPP59F:309:1124)
    at qs (gtm.js?id=GTM-WJPP59F:314:20)

Any help would be much appreciated thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source