The usage of eval () function in JavaScript

Source: Internet
Author: User
Tags eval opening and closing tags

Definition and usage the eval () function computes a string and executes the JavaScript code in it.

The syntax eval (string) argument describes string as required. The string to evaluate, which contains the JAVASCRIPT expression to evaluate or the statement to execute. The return value is computed by calculating the value of string (if any).

Indicates that the method accepts only the original string as a parameter, and if the string argument is not the original string, the method returns without any changes. Therefore, do not pass a String object as an argument for the eval () function.

If you attempt to overwrite the Eval attribute or assign the eval () method to another property and call it through this property, the ECMAScript implementation allows a Evalerror exception to be thrown.

Throws an SyntaxError exception if there are no valid expressions and statements in the argument.

If Eval () is invoked illegally, a Evalerror exception is thrown.

If the Javascript code passed to eval () generates an exception, eval () passes the exception to the caller.

Hint and comment tip: Although the eval () is very powerful, it is not much used in practice.

eg

The code is as follows Copy Code

<script language= "JavaScript" >
function Showsubmenu (SID)
{
Whichel = eval ("submenu" + SID);
if (WhichEl.style.display = "None")
{
Eval ("submenu" + Sid + ". style.display=" ";");
}
Else
{
Eval ("submenu" + Sid + ". style.display=" None ";");
}
}
</SCRIPT>

Format of JSON

The format of JSON is made up of curly braces and a name-value pair consisting of a colon (:). Note the difference between the JSON format and the object literal: The literals of the JSON name is strictly expressed in quotes + names.

Give an example to explain

The literal amount of the object

  code is as follows copy code
var objectliteral = {  Name: "OBJECTOR.L",  Age: ", " special Ascript ",  sayname:function () {    return this.name; }}; JSON Object
var jsonformat = {  "Summary": "Blogs",  "blogrolls": [    {        "title": "Explore JavaScript",       "link": "http://example.com/"    },    {        "title": "Explore JavaScript",        "link": "http://example.com/"    } ]}; Eval and JSON

Thanks to the rise of Ajax, the lightweight data format of JSON became increasingly popular as a transfer format between the client and the server, and the problem was how to convert the server-side-built JSON data into usable JavaScript objects. Using the Eval function is undoubtedly a simple and straightforward approach. When converting, you need to wrap the outside of the JSON string in parentheses:

The code is as follows Copy Code

var jsonobject = eval ("+ Jsonformat +")); Why do I have braces?

The purpose of parentheses is to force the Eval function to force an expression in parentheses (expression) into an object when evaluating JavaScript code, rather than as a statement (statement). For example, an object literal {}, if the outer bracket is not added, Eval recognizes the curly braces as the opening and closing tags of the JavaScript code block, then {} will be considered to have executed an empty statement. So the following two execution results are different:

The code is as follows Copy Code

Alert (eval ("{}");//Return Undefinedalert (eval ("({})"),//return Object[object] The name part of JSON format Why do I need quotes?

Because the Eval function interprets {foo: "Bar"} as a legitimate JavaScript statement, not an expression. But what people tend to want is for eval to interpret this code as an object. So the JSON format will force you to add quotes and parentheses around the outside of the name so that Eval does not incorrectly interpret JSON as a block of code.

Give an example to explain

Eval Error parsing semantics

The code is as follows Copy Code
Alert (eval (' {foo: ' Bar '} ')); Return "bar", incorrect eval parse JSON correctly
Alert (eval ({"foo": "Bar"})); Return JSON object, correct conclusion

Understand how Eval works and the strict qualifying format of JSON, which is a logical combination of data delivery and object conversions that Eval and JSON apply to JavaScript.

The code is as follows Copy Code

Following this format:

Eval (' {' + jsonstring + ') ');


Attention to security issues

Analyze and summarize a bug that was a long time ago

The code is as follows Copy Code

      function Parsepost (data, action) {
         try {
& nbsp;            var postdata = eval ("+ Data +"));
            
             /To DO1
        } catch (E) {
            
             /To DO2
        }
    }


This is a page of the old code, data is the database body field, both user input and out of the data, due to the business relationship, data is saved in JSON format, in order to enable the data to achieve compatibility, here use Try...catch ... method, if the variable data can be converted to an object, execute to DO1, otherwise execute to DO2.
We know that Eval's role is simply to pass a string to the JS parser, which is interpreted by the JavaScript parser as JavaScript code and executed. But it's also very dangerous, especially if you pass the user input data to it, This is often a point of entry for malicious users.
Install the above code, if the user input data is a paragraph of JS code, such as "alert (' Hello ')", then this code in the database after the display part of the eval ("alert (' Hello ')"), My page will then bounce out of the alert box.

Well, this is what everyone knows Cross-site scripting (XSS), Chinese translation is a cross-site scripting attack.

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications which allow Co De injection by malicious Web users to the Web pages viewed by other users. Examples of such code include HTML code and Client-side scripts. (Excerpt from "Cross-site scripting" http://en.wikipedia.org/wiki/Cross-site_scripting) here is a description of XSS's background, type, utilization and precautions.

Start the repair work below. This code is clearly not able to make strict judgments about data, data is not only the user input, but also to be the evil of the eval () function execution, and the entire process does not have user input data for a checksum, this is the problem, and the problem is quite serious.

According to the business logic of this code of the following system, the logical structure can be determined by judging the data type, and the changed code is as follows:

The code is as follows Copy Code

function Parsepost (data, action) {
if (typeof (data) = = ' String ') {

To DO2
}
else {
To DO1
}
}


The code is modified on the subject as above, our choice is to bypass the eval () function, assign the body's prototype to the JAVASCRIPT variable data, and then use typeof () to judge the data and proceed with the next step based on this judgment.
Alternatively, you can use the JSON parser to parse the JSON and download the reference implementation script from http://www.json.org/json.js. JSON is a text-based, Open Data Interchange Format (see RFC 4627).

PS: This bug occurred in 2008, thread is subject to XSS attack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.