15

I have a textarea where user can enter javascript code which upon press of the button would be passed to eval().

I am having trouble catching the referenceError for cases when a user enters something like this:

var myName = Maria;

instead of

var myName = "Maria";

Thank you for you time!

jacobdo
  • 1,605
  • 3
  • 15
  • 34
  • An user entered value is always a string. – Suresh Atta Sep 12 '15 at 09:28
  • @sᴜʀᴇsʜᴀᴛᴛᴀ _user can enter javascript code which upon press of the button would be **passed to eval()**._ – Grundy Sep 12 '15 at 09:31
  • 1
    You need to be **VERY CAREFUL** with `eval()` and executing user code in the browser, please make sure you know what you're doing before using anything like this in production – hammus Sep 12 '15 at 09:31
  • 1
    You have misunderstood me - user does not just enter the name, but the entire js line i.e. var myName = ... which then gets executed in js via eval(), so user can pass anything. So when a user forgets quotes around the string, js throws referenceError which i need to catch because I want to code to continue running and give user feedback. – jacobdo Sep 12 '15 at 09:32
  • For those concerned, I am well aware of the risks related to eval() – jacobdo Sep 12 '15 at 09:33
  • @Grundy Your guess is true. OP is evaluating JS only :) – Suresh Atta Sep 12 '15 at 09:42
  • @leemo OP evaluating Javascript. No other option probably. – Suresh Atta Sep 12 '15 at 09:43

2 Answers2

29

Ok, as you said you understood the pit's of eval(), here i'm proposing a solution.

try {
    var myName = Maria;
} catch (e) {
    if (e instanceof ReferenceError) {
        // Handle error as necessary
    }
}
Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
7

Try putting a try/catch block around the eval() call. Like this:

try {
    eval(userInput);
} catch (e) {
    // do something
}

(Note that passing user input to eval() is NOT something you should do on a real site, for security reasons.)

ecraig12345
  • 2,328
  • 1
  • 19
  • 26