Use the setTimeout Function We can also pass in the JavaScript code string into the setTimeout function to run the code string. To do this, we write: const code = "alert('Hello World'); let x = 100"; setTimeout(code, 1); We pass code as the first argument of the setTimeout function to run it.
function ExecuteJavascriptString() { var s = "alert('hello')"; // how do I get a browser to alert('hello')? }
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
Whenever the JavaScript engine receives a script file, it first creates a default Execution Context known as the Global Execution Context (GEC) . The GEC is the base/default Execution Context where all JavaScript code that is not inside of a function gets executed. For every JavaScript file, there can only be one GEC.
With the eval
function, like:
eval("my script here");
You can execute it using a function. Example:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
The eval
function will evaluate a string that is passed to it.
But the use of eval
can be dangerous, so use with caution.
Edit: annakata has a good point -- Not only is eval
dangerous, it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.
Use eval().
W3 Schools tour of eval. Site has some usable examples of eval. The Mozilla documentation covers this in detail.
You will probably get a lot of warnings about using this safely. do NOT allow users to inject ANYTHING into eval() as it is a huge security issue.
You'll also want to know that eval() has a different scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With