diff --git a/datalayer.module b/datalayer.module index 495fffa..f22729c 100644 --- a/datalayer.module +++ b/datalayer.module @@ -125,6 +125,30 @@ function datalayer_page_attachments(array &$attachments) { $attachments['#attached']['library'][] = 'datalayer/helper'; } + + if (empty($attachments['#attached']['html_head'])) { + $attachments['#attached']['html_head'] = []; + } + + $datalayer_attachment = datalayer_get_data_from_page(); + $attachments['#attached']['html_head'][] = [ + [ + '#type' => 'html_tag', + '#tag' => 'script', + // Use json_encode() instead of + // Drupal\Component\Serialization\Json::encode() because we want to pass + // the additional JSON_UNESCAPED_UNICODE flag. + '#value' => 'window.dataLayer = window.dataLayer || []; window.dataLayer.push(' . json_encode($datalayer_attachment, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) . ');', + ], + 'datalayers-js', + ]; + + // If we're exposing user data make sure that context is added to the + // cachability for the page. And, we add this regardless of configuration + // becasue in datalayer_get_data_from_page() we always add userUid no matter + // what. + $attachments['#cache']['contexts'][] = 'user'; + // Output configured language data. $languages = \Drupal::languageManager()->getLanguages(); if (count($languages)) { diff --git a/src/DatalayerLazyBuilders.php b/src/DatalayerLazyBuilders.php index af79708..807d7a2 100644 --- a/src/DatalayerLazyBuilders.php +++ b/src/DatalayerLazyBuilders.php @@ -57,7 +57,7 @@ class DatalayerLazyBuilders implements TrustedCallbackInterface { // Use json_encode() instead of // Drupal\Component\Serialization\Json::encode() because we want to pass // the additional JSON_UNESCAPED_UNICODE flag. - '#value' => 'window.dataLayer = window.dataLayer || []; window.dataLayer.push(' . json_encode($datalayer_attachment, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) . ');', + // '#value' => 'window.dataLayer = window.dataLayer || []; window.dataLayer.push(' . json_encode($datalayer_attachment, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) . ');', ]; return $build; }