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);