Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda