Adding dynamically JavaScript code with eval
JavaScript has a function to create code dynamically and the code may contain variables, objects and functions.This code is stored in a string that is given as an argument to the built-in function eval.
Eval may be used with JSON. This format is an alternative to XML that is easier in its definition and its use. Through a call to eval a JSON file can directly become a JavaScript object.
eval may be used to add code to the current script!
The simplest example of eval is in evaluating an expression:
var x = 10;
alert( eval('(x + 2) * 5'));
Click for testing. Must show 60.
But we can go further and add dynamically code, for exemple, an assignment:
var strvar = "var z = 5;";
function evalvar()
{
eval(strvar);
alert(z * 3);
}
Click to test the variable. Must show 15.
We can even add a function dynamically to be used by the running script
This dynamically creates the function myfun() with eval, and the test function usefun() will call this function and show the value it returns based on the argument that is given to it.
var strfun = "function myfun(arg) { return arg * 3; }";
eval(strfun);
function usefun(x)
{
var res = myfun(x);
alert(res);
}
Click to test the function. Must show 36.
Another example with both variables and a function:
<script>
var doc = "var x=5;var y=6;function mult(a){return a * y;}";
eval(doc);
document.write("x=" + x + "<br>");
document.write("y=" + y + "<br>");
document.write("mult(x)=" + mult(x) + "<br>");
</script>
These possibilities are of course especially interesting if the code is generated and added by the program based on calculations of new parameters and processing.
The eval function is not the only way to increase the current script, we can also generate a script and attach it to the document with the DOM's methods and run it during the processing.
eval has a global or local scope
Used in a local context, the function eval will create objects whose
scope is limited to the context.
To give them a global scope, it is necessary to involve window with eval:
window.eval(...)
Or with a variable:
var gvar = this;
gvar.eval(...);
The variables declared in the argument eval will now be global.
Security: Warn to injected code
The eval function could be used to execute malicious code on Internet browsers. One must therefore be careful to check the possible uses of code that can be dynamically generated.
To eliminate any unwanted code, RFC 4627 provides a regular expression, however it does not impeach to change global variables or session variables.
But in fact, security issues arises only if the content comes from an external source, eg from an user through a text entry field.
See also
- JSON is used in the context of Ajax. See this tutorial of JSON and Ajax and the example that is provided.