3

I'm using the CSP module on my site and attempting to add a nonce to my GTM script.

I'm able to get a nonce value on the script element, e.g. <script nonce="zRaBCyoyymExSEt4jIfolw"> but that value never appears in my actual policy. I attempted to follow Altering a site's policy, but I'm confused on what I'm missing.

Here's my hook_page_attachments_alter().

function mytheme_page_attachments_alter(array &$attachments) {
  $js = "nonce-aware GTM script";
  $element = [
    '#type' => 'html_tag',
    '#tag' => 'script',
    '#value' => Markup::create($js),
  ];

  if (\Drupal::service('module_handler')->moduleExists('csp')) {
    $placeholderKey = Drupal::service('csp.nonce_builder')->getPlaceholderKey();

    // Add the nonce attribute to the element, with a placeholder value.
    $element['#attributes']['nonce'] = $placeholderKey;
    $element['#attached']['csp_nonce'] = [
      // Nonces can only be applied to script or style elements, so a shorthand key is available.
      // Values are an array of fallback sources.
      'script' => [Csp::POLICY_UNSAFE_INLINE],
    ];
    $element['#attached']['placeholders'][$placeholderKey] = [
      '#lazy_builder' => ['csp.nonce_builder:renderNonce', []],
    ];
    $attachments['#attached']['html_head']['custom_script'] = [
      $element,
      'custom_script',
      '#weight' => '-1000'
    ];
  }
}
1
  • I just want to thank you for this well-written question. It clearly explains the problem. It links to the official documentation followed. It includes the custom code. We so often do not see these attributes in questions, and people don't understand why they don't get answers. Commented Sep 26 at 14:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.