I need to execute Javascript using V8 in my C code. My C application access web server links and gets html data, images and javascript. For example, I have got 2 javascripts say js1.js and js2.js as shown below.
js1.js
function js_add_elements(var1, var2)
{
var var3 = parseInt(var1) + parseInt(var2);
var result = 'Addition of ' + var1 + ' and ' + var2 + ' results ' + var3;
return result;
}
js2.js
js_add_elements(2, 3);
Typically we need few objects to run javascript in V8. I have kept some contexts in global datastructure, I call it instance.
Instance level contexts
std::unique_ptr<v8::Platform> platform;
v8::Isolate::CreateParams create_params;
v8::Isolate *isolate;
v8::Isolate::Scope *isolate_scope;
and also I have kept some contexts as local members in a function as below.
Local contexts in a function
v8::HandleScope handle_scope;
v8::Local<v8::Context> context;
v8::Context::Scope context_scope;
v8::Local<v8::String> source;
v8::Local<v8::Script> script;
Keeping the contexts as above, I can run js1.js and js2.js and get desired result. Say after sometime I get js3.js from server and file looks as below.
js3.js
js_add_elements(5, 6);
js_add_elements(7, 8);
Now the problem starts. I will go and try to execute js3.js. By this time the contexts declared in local function are deleted (by garbage collector). When I try to execute js3.js, the contexts will be allocated newly and it would not have js1.js so it results undefined.
I hope there should be some way out to keep contexts alive for certain period. I am just not getting it.
Can somebody please help to learn how to keep context alive till certain time (say for lifetime of a session).