0

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

5
  • 1
    "API that required the code to be passed to it as a string" --- that's a terrible idea. Why do you need that? Commented Jun 22, 2015 at 23:04
  • @zerkms Well, its not really up to me to choose which API's I must use ;) Commented Jun 22, 2015 at 23:05
  • can't you just take function references? what is the end game? Commented Jun 22, 2015 at 23:09
  • In your second case you don't have a string containing code, so you wouldn't use evalScript at all. Did you just pick a bad example? Could you provide a better one? Commented Jun 22, 2015 at 23:12
  • @GEspinha okay. I though it's you who implement it that way. Commented Jun 22, 2015 at 23:49

4 Answers 4

1

take your function and append an empty string like this:

my_code += '';

Will coerce it to a string.

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

Comments

0

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

2 Comments

'\n' does not work like you think it does in js, String.fromCharCode(13) is what you have to do.
String.fromCharCode(13) is "\r", not "\n". For "\n" you'd use String.fromCharCode(10). That said, \r and \n both work, so there's no reason to resort to fromCharCode().
0

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)

Comments

0

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.

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.