1

I have got the following function coming from an ajax call which is stored in a string variable.

obj.action="DisplayActivity('modalDisplay', 0, 4);"

I am trying to run it but without success. I tried with:

eval(obj.action);

and with:

window[obj.action]

Any ideas? Thanks.

5
  • 1
    For that eval to work, DisplayActivity should be defined somewhere. Commented Jan 15, 2019 at 23:47
  • 1
    Does DisplayActivity actually exist? You may be getting some errors in your console if it doesn't. Commented Jan 15, 2019 at 23:48
  • jsfiddle.net/Lov981gy works fine. Commented Jan 15, 2019 at 23:48
  • 1
    eval works, of course only if the function you are trying to call is in scope. window[obj.action] makes no sense. Commented Jan 15, 2019 at 23:49
  • yes, for sure. the function is already defined. I can run it just calling like that DisplayActivity('modalDisplay', 0, 4); in the same code section. but i need to invoke it from the variable cos it is coming from the server side. Commented Jan 15, 2019 at 23:51

2 Answers 2

2

Try using New Function:

let s = "console.log('Hello '+a)",
call = new Function('a', s)

call('world!')

Make sure to avoid to call stuffs from a GET/POST or this will lead to be a typical xss, allowing to change your DOM from a special crafted link.

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

Comments

1

I suppose it's a scoping problem.

Try:

eval("global.tmp = function(DisplayActivity){" + obj.action + "};");
global.tmp(DisplayActivity);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.