6

Is there any alternative solution to create js-function from string var, except eval() and Function constructor I'm not allowed to use this both methods for security reason.

I know solution when you create DOM element with js code and add to page, but it's absolutely dirty hack. Thank you very much for help.

====

ADD

I received json-data with string like "a === b", "!a", "(a && b) || c" and so on... (hundreds of combinations). Need to create and return function which can do this compare function.

Something

var test = function ('a === b') {
  //some code without eval and new Function()
}
// in console
test('aa', 'bb') // return false
21
  • 1
    If you have access to file system, then create a new file, add the code inside it and load the JS file dynamically. Commented Jun 15, 2017 at 12:20
  • Whats the usecase? Commented Jun 15, 2017 at 12:20
  • 1
    @Jonasw I received json-data with string like "a === b", "!a", "(a && b) || c" and so on... (hundreds of combinations). Need to create and return function which can do this compare function Commented Jun 15, 2017 at 12:28
  • 3
    "I'm not allowed to use this both methods for security reason" — That's because of the inherent risks in turning strings into executable code, not because of those specific methods. Commented Jun 15, 2017 at 12:30
  • 1
    If it is for security reason, then webworkers can be an option as they create some sandbox. This answer can help you I guess stackoverflow.com/a/10372280/2745879 Commented Jun 15, 2017 at 12:34

1 Answer 1

6

Thanks all of you for interesting answers.

So, I had read and tried to use all methods, that you suggested me. All of them it’s eval() even you wont be used eval in your code. In my project I fixed problem using WebWorkers. This technologi has a lot benefits, please read article in MDN https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

But, I have to use "new Function" for this method.

So correct answer is:

You cannot create function from string without eval and new Function().

The only way it’s to write your own simple parser for that.

Thanks @brianxautumn

Sign up to request clarification or add additional context in comments.

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.