<script async src="https://www.googletagmanager.com/gtag/js?id=<key here>"></script> <script> const container = document.getElementById('app'); const key = container.getAttribute('secret-key'); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', key); </script> Estoy tratando de acceder a la clave que necesito para agregar Google Analytics dentro de la etiqueta <script> . Pude hacerlo en el segundo bloque de código usando
const container = document.getElementById('app'); const key = container.getAttribute('secret-key'); Quiero usar la misma clave para la primera cláusula <script> , pero no estoy seguro de poder hacer lo mismo para el <script> en línea. Quiero usar la misma const key para reemplazar <key here> .
¿Cómo puedo conseguir esto?
EDITAR
<script> function appendGAScriptTag() { const configKeys = JSON.parse(container.getAttribute('data-bootstrap')).common.conf; const gaKey = configKeys['GOOGLE_ANALYTICS_KEY']; let gaScriptTag = document.createElement('script'); gaScriptTag.type = 'text/javascript'; gaScriptTag.async = true; gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${gaKey}`; document.getElementsByTagName('head')[0].appendChild(gaScriptTag); } appendGAScriptTag(); // <--- calling it here </script>Puede crear dinámicamente la etiqueta <script> usando... ¡más JavaScript!
function appendGAScriptTag() { var gaScriptTag = document.createElement('script'); gaScriptTag.type = 'text/javascript'; gaScriptTag.async = true; gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${document.getElementById('app').getAttribute('secret-key')}`; document.getElementsByTagName('head')[0].appendChild(gaScriptTag); } Llama appendGAScriptTag() en tu código JavaScript preexistente cuando quieras inyectar el elemento generado en el DOM.