关于cef:cef-JS与C互调

46次阅读

共计 1357 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0