简体   繁体   中英

how to create REAL global object in v8?

I used v8 engine to create a program , it can run JS codes like :

alert('test');  // alert function is created in C++ and set global to v8 context. so it can be run.

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

But, if I set property to window object like :

window.name ='aa';

then, I visit it :

alert(name); // --------> this caused error that name is undefined...

In Chrome , we can set property , anything string for the window property name . it runs fine.

So how can I implement that ? it seems that the window is real global in JS context.

My code :

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;

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

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

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

//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 easy -_-!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM