Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
Accessing a variable inside an inline <script> tag in an html file with JavaScript
<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>

I am trying to access the key that I need to add Google Analytics inside the <script> tag. I was able to do it in the second block of code using

const container = document.getElementById('app');
const key = container.getAttribute('secret-key');

I want to use the same key for the first <script> clause, but I am not sure if I can do the same thing for the inline <script>? I want to use the same const key to replace the <key here>.

How can I achieve this?

EDIT

<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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could dynamically create the <script> tag using... more 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);
}

Call appendGAScriptTag() in your preexisting JavaScript code when you want to inject the generated element into the DOM.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda