0

Is it okay to do the following:

// Response from an API as a string, that contains a function to call.
const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

function myFunc(obj) {
  console.log(obj);
}

function callBack(stringFn) {
  return Function.prototype.call(stringFn);
}

callBack(stringFunc);

Console logs:

{"Status":200,"Message":"This is a message"}

It seems to work just fine, but wanted to know if this was the correct way to go about this at all? Are there any better methods or unforeseen implications?

Thanks

Michael Giovanni Pumo
  • 14,338
  • 18
  • 91
  • 140

2 Answers2

1

Use eval method.

<!DOCTYPE html>
<html>

<body>
    <script>
        const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

        function myFunc(obj) {
            console.log(obj);
        }

        function callBack(stringFn) {
            return Function.prototype.call(stringFn);
        }

        eval(stringFunc);
    </script>
</body>

</html>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • Why do you still have the callback() function though? Not needed if using eval(), right? – Michael Giovanni Pumo Jan 12 '17 at 13:25
  • No need of callBack if your intended to call myFunc only – Nitheesh Jan 12 '17 at 13:27
  • Note that using eval() or using any other way to execute code from a string is a serious security issue. When the string comes from an untrusted source, an attacker can execute anything in the context of your web page. You should not do that. – NineBerry Jan 12 '17 at 13:32
1

As an alternative to eval you can use the Function constructor:

const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

function myFunc(obj) {
  console.log(obj);
}

const payloadFunc = new Function(stringFunc);
payloadFunc() //logs the object
hackerrdave
  • 6,486
  • 1
  • 25
  • 29