Cef3中js与C++交互(五)—— JS简单回调

Native code can execute JS functions by using the ExecuteFunction()
and ExecuteFunctionWithContext() methods. The ExecuteFunction() method
should only be used if V8 is already inside a context as described in
the “Working with Contexts” section. The ExecuteFunctionWithContext()
method allows the application to specify the context that will be
entered for execution.

本地代码可以通过ExecuteFunction()和ExecuteFunctionWithContext()执行JS函数。ExecuteFunction()方法只能在V8对象已经在一个context中时才能进行调用,ExecuteFunctionWithContext()允许程序指定context进入并且执行该函数。

https://bitbucket.org/chromiumembedded/cef/wiki/JavaScriptIntegration.md

套路

(1)在 OnJSBinding()中创建一个"register"函数

void MyRenderProcessHandler::OnContextCreated(
    CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefFrame> frame,
    CefRefPtr<CefV8Context> context) {
   
  // Retrieve the context's window object.
  CefRefPtr<CefV8Value> object = context->GetGlobal();

  CefRefPtr<CefV8Handler> handler = new MyV8Handler(this);
  object->SetValue("register",
                   CefV8Value::CreateFunction("register", handler),
                   V8_PROPERTY_ATTRIBUTE_NONE);
}

(2)在MyV8Handler::Execute()的实现中对"register"的context和function保存引用

bool MyV8Handler::Execute(const CefString& name,
                          CefRefPtr<CefV8Value> object,
                          const CefV8ValueList& arguments,
                          CefRefPtr<CefV8Value>& retval,
                          CefString& exception) {
   
  if (name == "register") {
   
    if (arguments.size() == 1 && arguments[0]->IsFunction()) {
   
      callback_func_ = arguments[0];
      callback_context_ = CefV8Context::GetCurrentContext();
      return true;
    }
  }

  return false;
}

(3)通过JavaScript注册JS callback

<script language="JavaScript">
function myFunc() {
   
  // do something in JS.
}
window.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值