学习上篇文章后,在js中可以调用cef的方法。js的回调注册就是通过将js的方法通过window绑定的方法注册到cef中的。方法的调用是需要等待的,是同步的。
1. cef声明注册函数register
首先根据上个博客方法相同,在cef中构建一个register方法。
注册函数的第一个参数是回调方法,后面需要通过这个回调方法执行方法。
bool CV8JsHandler::Execute(const CefString& funcName,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (funcName == "register")
{
if (arguments.size() == 1 && arguments[0]->IsFunction())
{
CefRefPtr<CefV8Value> callbackFunc = arguments[0];
CefRefPtr<CefV8Context> callbackContext = CefV8Context::GetCurrentContext();
CefV8ValueList args;
args.push_back(CefV8Value::CreateInt(3));
args.push_back(CefV8Value::CreateInt(4));
//retval = callbackFunc->ExecuteFunctionWithContext(callbackContext, object, args);
retval = callbackFunc->ExecuteFunction(NULL, args);
QMessageBox::information(nullptr, "title", QString("%1").arg(retval->GetIntValue()));
return true;
}
}
2. js中声明注册函数registerfunction
//声明回调函数
function registerfunction( a, b) {
return a + b + 1;
}
function registerCallBack()
{
// 完成向cef注册回调函数
alert("registerCallBack:" + window.register(registerfunction) );
}
3. 使用回调函数
此时allbackFunc->ExecuteFunctionWithContext(callbackContext, object, args) 等价与registerfunction(3,4)。
CefV8ValueList args;
args.push_back(CefV8Value::CreateInt(3));
args.push_back(CefV8Value::CreateInt(4));
//retval = callbackFunc->ExecuteFunctionWithContext(callbackContext, object, args);
retval = callbackFunc->ExecuteFunction(NULL, args);