1

Using embedded SpiderMonkey in my C++ application I would like to extract all the strings from JavaScript code. JavaScript code looks something like this:

var foo = "something";  
var space = " ";  
var bar = foo + space + "beautiful";  

C++ code looks like this:

char *script = "var foo = \"something\"; var space = \" \"; var bar = foo + space + \"beautiful\";";
ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, &rval);

So my questions is, after SpiderMonkey executes JavaScript, how can I extract the string from variable bar (extracted value should be "something beautiful") and use it in my regular C++ code? I guess I have to evaluate the script first and then somehow extract the string from the JavaScript variable. I don't know how to extract the string using SpiderMonkey.

My second question:
http://siliconforks.com/doc/parsing-javascript-with-spidermonkey/
This SpiderMonkey JavaScript parser is written for SpiderMonkey 1.6. How can this be done with latest SpiderMonkey, because APIs for parsing have changed?

Thnx in advance,
Goran

Goran
  • 143
  • 2
  • 7
  • Please be more clear on the context in which you need to extract. If you are talking about passing content of client-side JS variables to server side C++ you need to send the vars to the server using http (ajax, form) – mplungjan Aug 31 '11 at 08:50
  • @mplungjan I wasn't very precise. I have embedded SpiderMonkey in my C++ app. Short snippet: char *script = "var foo = 'some string'"; ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, &rval); How can I now get to the value of JavaScript variable foo? – Goran Aug 31 '11 at 09:12
  • @mplungjan Updated. Do You know to solve my problem? Maybe You can give me some directions so I can investigate further? Thank You. – Goran Aug 31 '11 at 11:51
  • I think this is a duplicate http://stackoverflow.com/questions/639514/how-can-i-get-the-memory-address-of-a-javascript-variable More here: http://stackoverflow.com/search?q=spidermonkey+[c%2B%2B]+javascript+variable&submit=search I have no idea myself – mplungjan Aug 31 '11 at 14:22

2 Answers2

0

Since bar is property of global object, after the JS_EvaluateScript() I can use JS_GetProperty() function, something like this

JS_GetProperty(cx, global, "bar", &rval);
JSString *str = JS_ValueToString(cx, rval);
printf("%s\n", JS_EncodeString(cx, str));
Goran
  • 143
  • 2
  • 7
  • The above example NO LONGER WORKS with the latest Mozilla JavaScript version 38 or newer (both `js` and `xpcshell`) – John Greene May 23 '16 at 20:08
-1

Check String operation functions like subString. It can be used to resolve your query.

Umesh Patil
  • 10,475
  • 16
  • 52
  • 80