How to run javascript code represented by a string?

New Function(str)() or for JSON: new Function('return ' + str)(); If it happens to fit your needs any better than eval. It's still evil like eval.

The script is executed in the Client! – theateist Apr 11 at 17:07 Because most of the time you don't have control over eval()'d code. If that's not the case (if YOU are generating the code), it's fine.

If it's coming from ANYWHERE else you run risks of exposing yourself to any form of an XSS attack that may be applicable on your site. – cwolves Apr 11 at 17:09 thank you. I generate the code, so I control it.

Why Function is better than eval? Will function evaluate the code even that it contains NEWLINEs? – theateist Apr 11 at 17:15 no, it's the same.

The problem is that usually the reason for any server-generated code is to pass any data to the client (or why do you need it server-generated at all otherwise? ). If you don't do all necessary escaping, checking etc. A malicious user may misuse your eval() statement to inject code and he can do whatever is possible with JavaScript.

Just google for "evil eval" and you'll find lots of info. – Udo G Apr 11 at 17:25.

Just remove those parenthesis: eval(str); asssuming that you made a typo in your question and your server is sending the missing end parenthesis and comma within the object: Plugins. Add('test', function() { return { html: 'test.

Indeed, better to use JSON.parse() – Jim Blackler Apr 11 at 16:57 The comma and missing parenthesis are NOT the problem(Updated the post). I just missed them in the post. I tried eval with AND without parenthesis, this is not working.

– theateist Apr 11 at 17:06 move the { to the same line as the return and it will work. I've updated my solution accordingly. – Udo G Apr 11 at 17:17.

You are missing a comma in your object literal. Return on its own line will simply drop out of the function. I assume you want to return the object.

You need to specify the return value on the same line. Plugins. Add('test', function() { var ret = { html: 'test', width: 200, } return ret }.

Return { followed by a line-break and the rest of the object works too. – cwolves Apr 11 at 16:59 right, but you have some typos in your code (one excess comma, two semicolons missing and the end parenthesis missing). :-) – Udo G Apr 11 at 17:21.

You could return your string with a content type of "text/javascript" or "application/x-javascript" - the return value will be executed as JavaScript as soon as it is returned.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions