Hi,
I was needed to set different dataLayer variable for different pages before Google Tag init. By default dataLayer is cached and the same on all pages. I couldn't find any hook or methods to alter dataLayer. So I added hook to alter dataLayer before attaching this variable on the page. May be it's not the best place to alter dataLayer, because you need to create text for javascript variable. It will be better to alter array for dataLayer.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

levmyshkin created an issue. See original summary.

levmyshkin’s picture

I used this patch:

solotandem’s picture

Status: Active » Needs work

I agree with you it would be preferable to edit the array not the string.
The patch does not provide anything more than can already be done with hook_page_attachments_alter().
Both hooks would involve editing the JS string.

function mymodule_page_attachments_alter(&$attachments) {
  foreach ($attachments['#attached']['html_head'] as $index => &$item) {
    if ($item[1] == 'google_tag_data_layer_tag') {
      // Modify contents of string.
      mymodule_datalayer_modify($item[0]['#value']);
    }
  }
}

As on-the-fly changes to datalayer seem to be the purview of the datalayer project, perhaps you could use it for this purpose.