Skip to content

Instantly share code, notes, and snippets.

@L1fescape
Last active October 27, 2015 18:39
Show Gist options
  • Save L1fescape/97338069b0609ec52dbc to your computer and use it in GitHub Desktop.
Save L1fescape/97338069b0609ec52dbc to your computer and use it in GitHub Desktop.
Add console.log to v8
// ... import v8 ...
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() < 1) return;
HandleScope scope(args.GetIsolate());
Handle<Value> arg = args[0];
String::Utf8Value value(arg);
printf("%s\n", *value);
}
int main(){
// ... setup and initialize v8 with isolates and scopes ...
// create a template for the global object
Local<ObjectTemplate> global = ObjectTemplate::New(isolate);
// create a console object
Local<ObjectTemplate> console = ObjectTemplate::New(isolate);
// add a `log` property with a callback as its value
console->Set(String::NewFromUtf8(isolate, "log"), FunctionTemplate::New(isolate, LogCallback));
// add console to the global object
global->Set(String::NewFromUtf8(isolate, "console"), console);
// ...
}
@jijo2010
Copy link

I have tried the code and its not working with latest v8(v8-version,4,8,0,0,1), so i changed as below

static void LogCallback(const v8::FunctionCallbackInfov8::Value& args) {
if (args.Length() < 1) return;
HandleScope scope(args.GetIsolate());
Local arg = args[0];
String::Utf8Value value(arg);
printf("%s\n", *value);
}

// create a template for the global object
Local<ObjectTemplate> global = ObjectTemplate::New(isolate);

// create a console object
Local<ObjectTemplate> console = ObjectTemplate::New(isolate);
// add a `log` property with a callback as its value

console->Set(String::NewFromUtf8(isolate, "log", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, LogCallback));

// add console to the global object
global->Set(String::NewFromUtf8(isolate, "console",NewStringType::kNormal).ToLocalChecked(), console);

// Create a new context.
Local<Context> context = Context::New(isolate, NULL, global);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment