gespinha
gespinha

Reputation: 8487

javascript run function as a string

I am developing for an API that required the code to be passed to it as a string, for it to run, like this:

var api = [API ID],
    code = "alert('some text')";

api.evalScript(code);

But I have a lot of code to pass at the same time, how can I pass an entire function like that?

    var api = [API ID];

    function my_code(){
       alert('one');
       alert('two');
       alert('three');
    }

    api.evalScript(my_code());

This doesn't work

Upvotes: 0

Views: 73

Answers (4)

dreamlab
dreamlab

Reputation: 3361

you are passing the code as a function, not a string.

var my_code = "alert('one');\n" +
              "alert('two');\n" + 
              "alert('three');"


api.evalScript(my_code);

the newlines are optional

Upvotes: 0

celticminstrel
celticminstrel

Reputation: 1679

Assuming that you're passing code to the API that will be executed at some later point that the API determines, and you have a function that you want the API to execute, you can probably just pass "mycode()" to the API.

However, if you intend the code to be executed immediately, it doesn't appear that there's any reason to use the API at all, so you could just call my_code() directly.

Upvotes: 0

inorganik
inorganik

Reputation: 25525

take your function and append an empty string like this:

my_code += '';

Will coerce it to a string.

Upvotes: 1

msarchet
msarchet

Reputation: 15242

Ignoring the security implications here.

So evalScript probably wants a strings, where you're trying to eval a function and that isn't going to work so well.

Let's talk about how to easily concat a large string in JS.

var myCode = [
   'alert("one");',
   'alert("two");',
   'alert("three");'
].join('');

api.evalScript(myCode)

Upvotes: 0

Related Questions