JS调用C++函数
- (1)继承CefRenderProcessHandler
- (2)重写OnContextCreated虚函数
- (3)绑定值或者JS对象(数组)到window对象上
- (4)在js中访问window对象上绑定的值(或者JS对象、数组等)
// Called immediately after the V8 context for a frame has been created. To
// retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal()
// method. V8 handles can only be accessed from the thread on which they are
// created. A task runner for posting tasks on the associated thread can be
// retrieved via the CefV8Context::GetTaskRunner() method.
///
/*--cef()--*/
virtual void OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
OnContextCreated接口实在chrome的V8引擎创建后调用的,在这里我们需要将JS里面调用的函数和C++的执行函数关联起来,这样JS就可以“执行”C++代码了。
我们的函数都是定义在window对象中的,根据注释我们需要GetGlobal获取这个对象。
void SimpleApp::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
// The var type can accept all object or variable
CefRefPtr<CefV8Value> window = context->GetGlobal();
// bind value into window[or you can bind value into window sub node]
CefRefPtr<CefV8Value> strValue = CefV8Value::CreateString("say yes");
window->SetValue("say_yes", strValue, V8_PROPERTY_ATTRIBUTE_NONE);
}
CefRefPtr<CefV8Handler> myV8handle = new CCefV8Handler();
CefRefPtr<CefV8Value> myFun = CefV8Value::CreateFunction(L"SetAppState", myV8handle);
static_cast<CCefV8Handler*>(myV8handle.get())->AddFun(L"SetAppState", &CChromeJsCallback::JsSetAppState);
pObjApp->SetValue(L"SetAppState", myFun, V8_PROPERTY_ATTRIBUTE_NONE);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。