How to create a REAL global object in v8?

I used the v8 engine to create a program, it can run JS codes, for example:

alerts ('test'); // alert function is created in C ++ and sets the global context v8. therefore it can be started.

window.name = 'aa'; // the window object is exported from C ++ to v8.

But, if I set a property for the window object, for example:

window.name = 'aa';

then i find it:

alerts (name); // --------> this caused an error whose name is undefined ...

In Chrome, we can set a property, any string for the window property name. It works fine.

So how can I implement this? the window seems to be real global in the JS context.

My code is:

Isolate* isolate = Isolate::GetCurrent(); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Handle<ObjectTemplate> global = ObjectTemplate::New(isolate); v8::Handle<v8::FunctionTemplate> log_ft = v8::FunctionTemplate::New(isolate, log_Callback); log_ft->InstanceTemplate()->SetInternalFieldCount(1); global->Set(isolate, "alert", log_ft); Handle<Context> context = Context::New(isolate, NULL, global); Context::Scope context_scope(context); // set global objects and functions Local<Object> obj( Object::New(isolate)); context->Global()->Set( String::NewFromUtf8(isolate, "window"), obj ); runJSCode(context, (char*)"window.name =33; alert(name);"); std::cout << "********* v8 executed finished !! ********** \n"; return 0; 
+5
source share
2 answers

I think you need to call "alert" with "window.name" instead of "name".

 runJSCode(context, (char*)"window.name =33; alert(window.name);"); 

"window.name" means the "name" property of the "window" object, but simply "name" means the name of the objet property "this" (that is, in this case, the object you get by calling "context-> Global ()" in the code C ++). You set the window as a property of a global object, not as a global object.

0
source
 //Local<Object> obj( Object::New(isolate)); //context->Global()->Set( String::NewFromUtf8(isolate, "window"), obj ); runJSCode(context, (char*)"window=this; window.name =33; alert(name);"); 

==== so simple -_-!

-2
source

Source: https://habr.com/ru/post/1207089/


All Articles