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

174
Visualizações
Hot to read variable that is outside dynamically added script element?

I add scripts dynamically to my page using next code:

var newScriptElem = document.createElement("script");
newScriptElem.innerHTML = myJSCodeString; // myJSCodeString loaded before from .js separate file.
parentElement.appendChild(newScriptElem);

The code inside does get called and works mostly fine, but I'm not able to get any variables outside that block. I have one singleton object loaded before by manually added using <script src="app.js"> tag. It has global variable, that I want to read.

It works fine if I add the code in script tag right inside HTML file, but it does not work if I try to get it from dynamically loaded script.

Here is what app.js looks like, basically:

var app = new App();
function App(){
  this.someVar = 2;
}

This one does work

<body>
  <script src="js/app.js"></script>
   <script>
     console.log(app); // Outputs App Obj
   </script>
</body>

But this does not:

var newScriptElem = document.createElement("script");
newScriptElem.innerHTML = "console.log(app)"; // Outputs "undefined"
parentElement.appendChild(newScriptElem);

Is there any way to read global variables from a scope of a dynamically added script element?

P.S. I try to use Cordova, by the way, but it does not work in Chrome browser anyway..

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your question you are not appending the script that you have generated.

<script>
var foo = 1;
var newScriptElem = document.createElement("script");
newScriptElem.innerHTML = `console.log(${foo});`;
document.body.append(newScriptElem);
console.log("loaded");
</script>

about 4 years ago · Juan Pablo Isaza Relatório

0

One solution, as @Bergi mentioned, is to call eval(myJSCodeString), instead of adding it as a <script> block.

That way the code will be executed as is, and global variables will be accessible.

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