From 07d3724a46de3c570bf07313b006cb3c0c713b8c Mon Sep 17 00:00:00 2001 From: Alan Willms Date: Mon, 23 Mar 2020 16:43:20 -0300 Subject: [PATCH] Fix bug when data layer name contains unexpected characters --- src/Snippets.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Snippets.js b/src/Snippets.js index b798e3db..db8ea2c5 100644 --- a/src/Snippets.js +++ b/src/Snippets.js @@ -8,11 +8,11 @@ const Snippets = { const gtm_preview = `>m_preview=${preview}` if (!id) warn('GTM Id is required') - + const iframe = ` ` - + 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)}}); @@ -20,9 +20,9 @@ const Snippets = { 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); })(window,document,'script','${dataLayerName}','${id}');` - + const dataLayerVar = this.dataLayer(dataLayer, dataLayerName) - + return { iframe, script, @@ -30,10 +30,11 @@ const Snippets = { } }, dataLayer: function (dataLayer, dataLayerName) { + const escapedDataLayerName = JSON.stringify(dataLayerName) return ` - window.${dataLayerName} = window.${dataLayerName} || []; - window.${dataLayerName}.push(${JSON.stringify(dataLayer)})` + window[${escapedDataLayerName}] = window[${escapedDataLayerName}] || []; + window[${escapedDataLayerName}].push(${JSON.stringify(dataLayer)})` } -} +} module.exports = Snippets