3

I'm creating a map editor for my game, and I added feature which is adding script to map (textarea), then code writed by person which is editing a map is saved to variable, and then when this person save map, this variable is saved to JSON file as variable in Map object.

When map is loading in the game, this code is transforming into Function object and then it's launching.

My question is: Is there option to check is this string valid JavaScript, and if not alert("Error" + error) or something like that?

// Editor is only for developers, not for users, so I don't need to check it on server-side for safety

7
  • perhaps this would help Commented Dec 25, 2016 at 11:53
  • But what will eval() return if string will be not correct? Commented Dec 25, 2016 at 11:56
  • Just make sure that it is correct. Also avoid using eval Commented Dec 25, 2016 at 12:00
  • Can you do this on server side or must it be on the client ? Commented Dec 25, 2016 at 12:04
  • About the given answers, evaling some arbitrary user input is pretty much the same as you'd hit your head with a hammer. What a splendid opportunity for an attacker. Better to validate the string at the server-side. Commented Dec 25, 2016 at 12:14

2 Answers 2

4

You could do the following :

try {
  eval("function f () {"
  + "user code here"
  + "}");
} catch (e) {
  console.log(e+"");
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can wrap eval in a try catch to validate a JS string. This is how it will work. enter image description here

Invalid JS string will through an uncaught reference error. It would look something like:

try {
   eval('console.log("a")');
   console.log('Valid JS');
} catch (e) {
   console.log('Invalid JS');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.