Home > Net >  Hot to read variable that is outside dynamically added script element?
Hot to read variable that is outside dynamically added script element?

Time:01-07

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..

CodePudding user response:

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>

CodePudding user response:

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.

  •  Tags:  
  • Related