Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!