admin管理员组

文章数量:1178553

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!

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!

Share Improve this question asked Sep 12, 2015 at 9:27 jacobdojacobdo 1,6154 gold badges16 silver badges34 bronze badges 7
  • An user entered value is always a string. – Suresh Atta Commented Sep 12, 2015 at 9:28
  • @sᴜʀᴇsʜᴀᴛᴛᴀ user can enter javascript code which upon press of the button would be passed to eval(). – Grundy Commented Sep 12, 2015 at 9: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 Commented Sep 12, 2015 at 9: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 Commented Sep 12, 2015 at 9:32
  • For those concerned, I am well aware of the risks related to eval() – jacobdo Commented Sep 12, 2015 at 9:33
 |  Show 2 more comments

2 Answers 2

Reset to default 30

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
    }
}

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.)

本文标签: javascriptCatch a referenceError in jsStack Overflow