Skip to content

gtm.js?id=xxx CSP error on checkout page

I have error ‘Refused to execute inline script because it violates the following Content Security Policy directive…’ in console.
I tried to solve this in the following ways

  1. In .phtml

    <script type="text/x-magento-init"> {"*": { "gtmLoader": { "gtmId": "<?= $viewModel->getGtmId(); ?>" } } } </script>

in js

define(['jquery'], function ($) {
"use strict";

return function (config) {
    window.dataLayer = window.dataLayer || [];
    $(document).trigger('gtm:beforeInitialize');
    (function (w, d, s, l, i) {
        w[l] = w[l] || [];
        w[l].push({'gtm.start': new Date().getTime(), event: 'gtm.js'});
        var f = d.getElementsByTagName(s)[0],
            j = d.createElement(s),
            dl = l != 'dataLayer' ? '&l=' + l : '';
        j.async = true;
        j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
        f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', config.gtmId);

    $(document).trigger('gtm:afterInitialize');
};

});

2.

<?php $scriptString = <<<script
(function (w, d, s, l, i) {
        w[l] = w[l] || [];
        w[l].push({'gtm.start': new Date().getTime(), event: 'gtm.js'});
        var f = d.getElementsByTagName(s)[0],
            j = d.createElement(s),
            dl = l != 'dataLayer' ? '&l=' + l : '';
        j.async = true;
        j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
        f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', '{$containerCode}');
script;
?><?= $secureRenderer->renderTag('script', [], $scriptString, false) ?>

But in both cases I have an error for gtm.js?id=xxx

Please tell me what I’m doing wrong