Search code examples
c++spidermonkey

How to execute user defined javascript code using spidermonkey


I have the following javascript code as string

std::string script = " { function execute() { var x=10; return x; } } ";

I want to evaluate this script and return the value , is there any way to do this?

Thanks in advance.


Solution

  • To evaluate a JS script you will need

    JSBool JS_EvaluateScript(JSContext *cx, JSObject *obj, const char *src, uintN length, const char *filename, uintN lineno, jsval *rval);
    

    As described here : JS_EvaluateScript - SpiderMonkey | MDN

    Then if you want to get the returned value you have to call the exectue function :

    "function execute(){ var x = 10; return x;} execute();"
    

    Then to evaluate the script have to be a const char* type not a std::string

    After evaluating the script you can get the returned value using rval

    if(JSVAL_IS_INT(rval))
      printf("The returned value is : %d\n", JSVAL_TO_INT(rval));