diff --git a/app/assets/javascripts/google-tag-manager.js b/app/assets/javascripts/google-tag-manager.js new file mode 100644 index 00000000000..ebc19ad1bff --- /dev/null +++ b/app/assets/javascripts/google-tag-manager.js @@ -0,0 +1,17 @@ +(function() { + const gtmDataElement = document.getElementById("data-google-tag-manager"); + const dataLayerJson = JSON.parse(gtmDataElement.dataset.dataLayer); + + // dataLayer declaration needs to precede the container snippet + // https://developers.google.com/tag-manager/devguide#adding-data-layer-variables-to-a-page + window.dataLayer = [dataLayerJson]; + + /* eslint-disable */ + // prettier-ignore + (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',gtmDataElement.dataset.containerId); + /* eslint-enable */ +})(); diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 2f6a1456c3a..f775b6e8428 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -31,7 +31,7 @@ module ApplicationHelper if SiteSetting.ga_universal_auto_link_domains.present? result[:allowLinker] = true end - result.to_json.html_safe + result.to_json end def ga_universal_json diff --git a/app/views/common/_google_tag_manager_head.html.erb b/app/views/common/_google_tag_manager_head.html.erb index 2320f2c7b02..8507a928321 100644 --- a/app/views/common/_google_tag_manager_head.html.erb +++ b/app/views/common/_google_tag_manager_head.html.erb @@ -1,11 +1,5 @@ - + - - - +<%= preload_script 'google-tag-manager' %> diff --git a/config/application.rb b/config/application.rb index 90218a83eb1..8687840329d 100644 --- a/config/application.rb +++ b/config/application.rb @@ -117,6 +117,8 @@ module Discourse plugin-third-party.js markdown-it-bundle.js service-worker.js + google-tag-manager.js + google-universal-analytics.js } # Precompile all available locales