Creating Javascript accessible object from C++ / CEF


Example with Chromium Embedded Framework (CEF) on how to create an object in C++ and make it accessible via Javascript.

Object {ready: true, version: "psql.0.0.1", info: Object, getVersion: function}
void ExtractEngineApp::OnContextCreated(
	CefRefPtr<CefBrowser> browser, 
	CefRefPtr<CefFrame> frame, 
	CefRefPtr<CefV8Context> context)
	auto info = CefV8Value::CreateObject(NULL, NULL);
	info->SetValue("major", CefV8Value::CreateString("0"), V8_PROPERTY_ATTRIBUTE_READONLY);
	info->SetValue("minor", CefV8Value::CreateString("1"), V8_PROPERTY_ATTRIBUTE_READONLY);
	auto global = context->GetGlobal();
	auto api = CefV8Value::CreateObject(NULL, NULL);
	global->SetValue("api", api, V8_PROPERTY_ATTRIBUTE_NONE);
	auto fun = CefV8Value::CreateFunction("getVersion", new engine:: PhantomExtensionHandler(this));
	api->SetValue("getVersion", fun, V8_PROPERTY_ATTRIBUTE_NONE);
	// Readonly properties
	api->SetValue("ready", CefV8Value::CreateBool(true), V8_PROPERTY_ATTRIBUTE_READONLY);
	api->SetValue("version", CefV8Value::CreateString("psql.0.0.1"), V8_PROPERTY_ATTRIBUTE_READONLY);
	// Readonly Object access
	api->SetValue("info", info, V8_PROPERTY_ATTRIBUTE_READONLY);
class PhantomExtensionHandler : public CefV8Handler
		explicit PhantomExtensionHandler(CefRefPtr<ExtractEngineApp> client_app)
			: client_app(client_app)
			, messageId(0)
		virtual bool Execute(const CefString& name,
			CefRefPtr<CefV8Value> object,
			const CefV8ValueList& arguments,
			CefRefPtr<CefV8Value>& retval,
			CefString& exception)
			if (name == "getVersion")
				retval = CefV8Value::CreateString("Version(SemVer) # 0.0.1");
			return true;
		CefRefPtr<ExtractEngineApp> client_app;
		int32 messageId;

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *