Magento | PHP | Shopify | WordPress Tutorial

Allow the execution of JavaScript in GTM is by adding a nonce to the script’s opening tag

Changes to do in Magento

  1. In your custom module, utilize CSP Nonce Provider and pass the nonce to the JavaScript. For more details, refer to Basic Template Concepts in the Adobe Commerce Developer documentation.
<?php
declare(strict_types=1);
namespace DSS\CSP\Block;
use Magento\Csp\Helper\CspNonceProvider;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
class AllPage extends Template
{
    /**
     * @param Context $context
     * @param CspNonceProvider $cspNonceProvider
     * @param array $data
     */
    public function __construct(
        Context $context,
        private readonly CspNonceProvider $cspNonceProvider,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $data
        );
    }
    /**
     * Get CSP Nonce
     *
     * @return String
     * @throws LocalizedException
     */
    public function getNonce(): string
    {
        return $this->cspNonceProvider->generateNonce();
    }
}
** @var \Vivo\CSP\Block\AllPage $block */
?>
<?php
$scriptString = <<<script
    window.cspNonce = ‘{$block->getNonce()}’;
script;
?>
<?= /* @noEscape */
$secureRenderer->renderTag(‘script’, [], $scriptString, false) ?>
<?xml version=“1.0”?>
<page xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
      xsi:noNamespaceSchemaLocation=“urn:magento:framework:View/Layout/etc/page_configuration.xsd”>
    <body>
        <referenceContainer name=“head.additional”>
            <block class=“DSS\CSP\Block\AllPage” template=“DSS_CSP::allpage.phtml” before=“-“ name=“gtm_all_page”/>
        </referenceContainer>
    </body>
</page>

3.This script sets a global variable cspNonce with the value of the current nonce, which can then be captured in Google Tag Manager variable and used to sign Custom HTML scripts to ensure they are allowed to execute under the CSP. It should be injected to all pages.

GTM Configuration


1. Create a Google Tag Manager Variable of the type JavaScript Variable


2. Modify your Custom HTML block that contains the JavaScript in GTM Containers Blocks.

< script nonce=“{{gtmNonce}}”>
                     console.log(“This is a test”);
              < /script>

3. Ensure that you check the Support document.write checkbox, as this is essential for the script to function correctly.


If your js executes any other js and in that case, in your script, you need to add cspnonce, example as below
s = document.querySelector(‘script’);t.setAttribute(‘nonce’,window.cspNonce);