diff --git a/src/Snippets.js b/src/Snippets.js index b798e3db..15dc5a94 100644 --- a/src/Snippets.js +++ b/src/Snippets.js @@ -3,7 +3,7 @@ import warn from './utils/warn' // https://developers.google.com/tag-manager/quickstart const Snippets = { - tags: function ({ id, events, dataLayer, dataLayerName, preview, auth }) { + tags: function ({ id, events, dataLayer, dataLayerName, preview, auth, nonce = undefined }) { const gtm_auth = `>m_auth=${auth}` const gtm_preview = `>m_preview=${preview}` @@ -13,12 +13,13 @@ const Snippets = { ` + const nonceLine = !!nonce ? `j.setAttribute('nonce','${nonce}');` : ''; const script = ` (function(w,d,s,l,i){w[l]=w[l]||[]; w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js', ${JSON.stringify(events).slice(1, -1)}}); 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+'${gtm_auth}${gtm_preview}>m_cookies_win=x'; - f.parentNode.insertBefore(j,f); + ${nonceLine}f.parentNode.insertBefore(j,f); })(window,document,'script','${dataLayerName}','${id}');` const dataLayerVar = this.dataLayer(dataLayer, dataLayerName) diff --git a/src/TagManager.js b/src/TagManager.js index 6c35942f..5d04654c 100644 --- a/src/TagManager.js +++ b/src/TagManager.js @@ -18,6 +18,9 @@ const TagManager = { const script = () => { const script = document.createElement('script') script.innerHTML = snippets.script + if (args.nonce) { + script.setAttribute('nonce', args.nonce); + } return script } @@ -29,20 +32,21 @@ const TagManager = { dataScript } }, - initialize: function ({ gtmId, events = {}, dataLayer, dataLayerName = 'dataLayer', auth = '', preview = '' }) { + initialize: function ({ gtmId, events = {}, dataLayer, dataLayerName = 'dataLayer', auth = '', preview = '', nonce = undefined }) { const gtm = this.gtm({ id: gtmId, events: events, dataLayer: dataLayer || undefined, dataLayerName: dataLayerName, auth, - preview + preview, + nonce }) if (dataLayer) document.head.appendChild(gtm.dataScript) document.head.insertBefore(gtm.script(), document.head.childNodes[0]) document.body.insertBefore(gtm.noScript(), document.body.childNodes[0]) }, - dataLayer: function ({dataLayer, dataLayerName = 'dataLayer'}) { + dataLayer: function ({ dataLayer, dataLayerName = 'dataLayer' }) { if (window[dataLayerName]) return window[dataLayerName].push(dataLayer) const snippets = Snippets.dataLayer(dataLayer, dataLayerName) const dataScript = this.dataScript(snippets)