Skip to content

Instantly share code, notes, and snippets.

@DominicWatts
Last active November 4, 2024 09:28
Show Gist options
  • Save DominicWatts/4cb2820d433bc0af84c1794a2712ea89 to your computer and use it in GitHub Desktop.
Save DominicWatts/4cb2820d433bc0af84c1794a2712ea89 to your computer and use it in GitHub Desktop.
Magento 2 : CSP inline scripts #magento2

Here's an example script to include in your phtml file, which will be whitelisted by CSP. You can use a similar method for other inline scripts:

    <?php
    /** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
    
    $scriptString = <<<script
    require(['jquery'],function($){
        $(document).ready(function() {
            zE('webWidget', 'setLocale', 'NB');
        });
    });
    script;
    ?>
    <?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>

Place this code in your phtml file, and it should resolve csp the error.

Alternative approach

Helper

/**
 * @return false|\Magento\Csp\Helper\CspNonceProvider
 */
public function getCspNonceProvider()
{
    if (class_exists(\Magento\Csp\Helper\CspNonceProvider::class)) {
        return  \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Csp\Helper\CspNonceProvider::class);
    }

    return false;
}

phtml

    <?php
    $_helper = $this->helper(\Vendor\Module\Helper\Data::class);
    /** @var \Vendor\Module\Helper\Data $_helper */
    $cspNonceProvider = $_helper->getCspNonceProvider();
    ?>
    <script <?php if ($cspNonceProvider) echo ' nonce="' .  $cspNonceProvider->generateNonce() . '" ' ?>>
    require(['jquery'],function($){
        $(document).ready(function() {
            zE('webWidget', 'setLocale', 'NB');
        });
    });
    </script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment