go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/gtm/gtm.go (about) 1 // Copyright 2023 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package gtm 16 17 // gtm.go has logic for generating Google Tag Manager (gtm.js) snippet. 18 19 import ( 20 "fmt" 21 "html/template" 22 "regexp" 23 ) 24 25 var rGTMAllowed = regexp.MustCompile(`^GTM-[A-Z0-9]+$`) 26 27 // makeGTMJSSnippet returns an HTML JS snippet for Google Tag Manager. 28 func makeGTMJSSnippet(containerID string) template.HTML { 29 return template.HTML( 30 fmt.Sprintf(` 31 <!-- Google Tag Manager --> 32 <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': 33 new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], 34 j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 35 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); 36 })(window,document,'script','dataLayer','%s');</script> 37 <!-- End Google Tag Manager -->`, 38 containerID, 39 ), 40 ) 41 } 42 43 // makeGTMNoScriptSnippet returns an HTML snippet for Google Tag Manager that 44 // works in a no-script context. 45 func makeGTMNoScriptSnippet(containerID string) template.HTML { 46 return template.HTML( 47 fmt.Sprintf(` 48 <!-- Google Tag Manager (noscript) --> 49 <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=%s" 50 height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> 51 <!-- End Google Tag Manager (noscript) -->`, 52 containerID, 53 ), 54 ) 55 }